4. Remove Duplicates from Sorted Array
easyAsked at FreshworksDeduplicate ticket IDs streaming in sorted order without allocating a second buffer.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array, remove duplicates in place such that each unique element appears once. Return the new length k. The first k elements of the array must hold the unique values in original order.
Constraints
1 <= nums.length <= 3 * 10^4Array is sorted non-decreasingMust mutate in place
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. Brute force
Copy uniques into a Set then back into the array.
- Time
- O(n)
- Space
- O(n)
const s = new Set(nums);
const out = [...s];
for (let i = 0; i < out.length; i++) nums[i] = out[i];
return out.length;Tradeoff:
2. Two pointers
Slow pointer marks the next unique slot; fast pointer scans. Write only when nums[fast] differs from nums[slow-1].
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let slow = 1;
for (let fast = 1; fast < nums.length; fast++) {
if (nums[fast] !== nums[fast - 1]) {
nums[slow++] = nums[fast];
}
}
return slow;
}Tradeoff:
Freshworks-specific tips
Freshworks frames this as deduping ticket IDs in a sorted queue — call out the in-place constraint up front since their SaaS backend hates extra allocations on hot paths.
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 Freshworks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →