4. Remove Duplicates from Sorted Array
easyAsked at MercuryRemove duplicates in-place from a sorted array and return new length.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted array nums, remove duplicates in-place such that each unique element appears only once. Return the new length, and the first k elements of nums should hold the unique values.
Constraints
1 <= nums.length <= 3*10^4Array is sorted ascending
Examples
Example 1
nums = [1,1,2]k=2, nums=[1,2,_]Example 2
nums = [0,0,1,1,1,2,2,3,3,4]k=5, nums=[0,1,2,3,4,_,_,_,_,_]Approaches
1. Set + rebuild
Dump to a Set, copy back into nums.
- Time
- O(n)
- Space
- O(n)
const uniq=[...new Set(nums)]; for (let i=0;i<uniq.length;i++) nums[i]=uniq[i]; return uniq.length;Tradeoff:
2. Two-pointer overwrite
Slow pointer holds next-write index; fast scans and writes only when value changes.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let k = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[i - 1]) {
nums[k++] = nums[i];
}
}
return k;
}Tradeoff:
Mercury-specific tips
At Mercury, this models dedup of ACH return notifications that the partner bank may re-emit on retry, so emphasize idempotent ledger writes keyed on the trace number.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Remove Duplicates from Sorted Array and other Mercury interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →