
Problem
Solution
Submissions
Remove Duplicates from Array
Certification: Basic Level
Accuracy: 100%
Submissions: 2
Points: 5
Write a JavaScript program to remove duplicates from a sorted array in-place. Return the length of the array after removing duplicates. The relative order of elements should be maintained, and you should modify the original array.
Example 1
- Input: nums = [1,1,2]
- Output: 2, nums = [1,2,_]
- Explanation:
- The array has duplicate 1's at positions 0 and 1.
- Keep the first occurrence of 1 and the unique element 2.
- The first 2 elements of the modified array are [1,2].
- Return length 2 as there are 2 unique elements.
- The array has duplicate 1's at positions 0 and 1.
Example 2
- Input: nums = [0,0,1,1,1,2,2,3,3,4]
- Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
- Explanation:
- The array has multiple duplicates.
- Keep only the first occurrence of each unique element.
- The first 5 elements become [0,1,2,3,4].
- Return length 5 as there are 5 unique elements.
- The array has multiple duplicates.
Constraints
- 1 ≤ nums.length ≤ 3 * 10^4
- -100 ≤ nums[i] ≤ 100
- nums is sorted in non-decreasing order
- You must modify the array in-place with O(1) extra memory
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two pointers approach - one slow pointer and one fast pointer
- The slow pointer keeps track of the position for the next unique element
- The fast pointer scans through the array to find unique elements
- Compare consecutive elements to identify duplicates
- When a unique element is found, place it at the slow pointer position
- Increment the slow pointer only when a unique element is placed
- Return the slow pointer value as it represents the length of unique elements