Problem Description
Given a non-strictly increasing (sorted with possible duplicates) integer aray nums, remove the duplicates in-place succh that each unique element appears only once. Maintain the relative order of the unique elements and return the number of unique elements in nums.
Let k be the count of unique elements. To pass the test cases:
- Modify
numsso that the firstkelements contain all unique elements in their original order. The remaining elements beyondkare irrelevant. - Return
k.
Test Case Validation
The system tests your solution with code like this:
nums = [...]
# Input array
k = removeDuplicates(nums)
# Function call
assert k == len(expectedNums), "Length mismatch"
for i in range(k):
assert nums[i] == expectedNums[i], f"Value mismatch at index {i}"
All assertions must pass for your solution to be accepted.
Examples
- Example 1: Input
nums = [1,1,2]→ Output2, modifiednums = [1,2,_] - Example 2: Input
nums = [0,0,1,1,1,2,2,3,3,4]→ Output5, modifiednums = [0,1,2,3,4]
Constraints
1 ≤ nums.length ≤ 3 × 10⁴-10⁴ ≤ nums[i] ≤ 10⁴numsis non-strictly increasing (sorted with duplicates allowed)
Solution: Two-Pointer Technique
Since nums is sorted, duplicates are consecutive, simplifying the problem. We use a two-pointer approach for O(n) time complexity and O(1) space complexity.
Algorithm Logic
- Initialize two pionters
leftandrightpointing to the start ofnums. - Traverse the array:
- If
nums[left] != nums[right], we found a new unique element. Incrementleft, then copynums[right]tonums[left]. - If
nums[left] == nums[right], skip this duplicate by just incrementingright. - Continue until
rightreaches the end of the array.
- If
- Return
left + 1as the count of unique elements.
Implementation
Python:
def remove_duplicates(nums):
left = 0
right = 0
while right < len(nums):
if nums[left] != nums[right]:
left += 1
nums[left] = nums[right]
right += 1
return left + 1
JavaScript:
var removeDuplicates = function(nums) {
let left = 0;
let right = 0;
while (right < nums.length) {
if (nums[left] !== nums[right]) {
left++;
nums[left] = nums[right];
}
right++;
}
return left + 1;
};