4. Remove Duplicates from Sorted Array
easyAsked at GojekRemove duplicates in place from a sorted array and return the count of unique elements.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return k, the number of unique elements; the first k slots of nums must contain those uniques.
Constraints
1 <= nums.length <= 3*10^4nums is sorted ascendingMust be done in-place with O(1) extra memory
Examples
Example 1
nums = [1,1,2]2, nums = [1,2,_]Example 2
nums = [0,0,1,1,1,2,2,3,3,4]5, nums = [0,1,2,3,4,_,_,_,_,_]Approaches
1. Set rebuild
Push elements into a Set, write back.
- Time
- O(n)
- Space
- O(n)
const u = [...new Set(nums)];
for (let i = 0; i < u.length; i++) nums[i] = u[i];
return u.length;Tradeoff:
2. Two pointers
Slow pointer holds last-written unique. Fast pointer scans ahead; advance slow when a new value appears.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let slow = 0;
for (let fast = 1; fast < nums.length; fast++) {
if (nums[fast] !== nums[slow]) {
slow++;
nums[slow] = nums[fast];
}
}
return slow + 1;
}Tradeoff:
Gojek-specific tips
Gojek expects you to default to in-place mutation since their courier-location buffers are tight on memory and copy-heavy code shows up as latency in dispatch.
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 Gojek interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →