Remove duplicates in-place such that each unique element appears only once.
Problem Statement
Given an integer array sorted in non-decreasing order, remove the duplicates in-place. Return the number of unique elements.
Examples
Input: arr = [1, 1, 2]
Output: 2
Explanation: Array becomes [1, 2, _]. Unique elements count is 2.
Constraints
Standard constraints
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
The array is already sorted. Duplicates will always be adjacent to each other.
š” Hint 2:
Use a two-pointer technique: one slow pointer k tracking the placement of unique elements, and a fast pointer i scanning.
š” Hint 3:
Whenever nums[i] !== nums[k - 1], write nums[k] = nums[i] and increment k.
Editorial & Approach
Problem Overview & Intuition
Because the input array is already sorted, all identical elements are placed consecutively. Using two pointers allows in-place overwriting of duplicates without allocating extra memory.
Step-by-Step Approach
- If
nums.length === 0, return0. - Initialize a write pointer
k = 1. - Iterate
ifrom1tonums.length - 1. - If
nums[i] !== nums[k - 1], placenums[k] = nums[i]and incrementk++. - Return
k, which is the count of unique elements.
Optimal Implementation (JavaScript)
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let k = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[k - 1]) {
nums[k] = nums[i];
k++;
}
}
return k;
}
Complexity Analysis
Time Complexity
O(N) ā single traversal of the input array.
Space Complexity
O(1) ā in-place modification with no extra data structures.
Edge Cases & Corner Traps Handled
- Empty array: returns 0.
- All elements unique: returns nums.length.
- All elements identical: returns 1.