-
Notifications
You must be signed in to change notification settings - Fork 382
Description
LeetCode Username
Rohan_k21
Problem Number, Title, and Link
- Remove Duplicates from Sorted Array https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
Bug Category
Missing test case (Incorrect/Inefficient Code getting accepted because of missing test cases)
Bug Description
Many accepted solutions use the condition including mine:
if i<1 or nums[j]>nums[i-1]:
to detect duplicates. This works only because the input array is guaranteed to be sorted in ascending order.
If the array were not sorted or sorted descending, this condition would fail to identify duplicates correctly. The more correct and clear condition is:
if i<1 or nums[j]!=nums[i-1]:
which works for all sorted arrays and clearly expresses the intent to skip duplicates.
Example failure case (not sorted):
nums = [3, 1, 2, 1, 3]
Using > will wrongly keep only the first element.
Suggestion:
Add clarification in the problem statement about the sorted order assumption and recommend using != in solutions for clarity and correctness.
Language Used for Code
C++
Code used for Submit/Run operation
class Solution{
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int i=1;
for (int j=1;j<nums.size();j++) {
if (nums[j]!=nums[i-1]){
nums[i]=nums[j];
i++;
}
}
return i;
}
};Expected behavior
Expected Behavior -
Given the problem “Remove Duplicates from Sorted Array” (LeetCode 26), the input array is expected to be sorted in non-decreasing order. The solution should remove duplicates in-place, preserving the order of unique elements and returning the new length of the unique portion.
For example, if the input array is sorted like [1, 1, 2], the output should have unique elements [1, 2] with the correct length 2.
What Should Happen?
The algorithm should correctly identify duplicates by comparing adjacent elements.
The solution should not rely on comparisons like nums[j] > nums[i-1] because it assumes strict ascending order and fails on arrays with equal elements.
Instead, the algorithm should use nums[j] != nums[i-1] to detect duplicates.
What Actually Happens?
Some accepted solutions use a condition like if (i < 1 or nums[j] > nums[i - 1]), which only works if the array is strictly increasing.
This approach fails for sorted arrays with duplicates or when the array is not strictly ascending.
If the array is unsorted, this condition fails completely to remove duplicates.
Suggested Improvement -
Add stronger clarification in the problem statement emphasizing the input array must be sorted.
Recommend solutions use != for comparison instead of >.
Consider adding additional test cases that test arrays with equal adjacent elements or confirm the array’s sorted property.
Screenshots
No response
Additional context
No response