4. Remove Duplicates from Sorted Array
easyAsked at GlassdoorDedupe a sorted array in place — Glassdoor uses this to test two-pointer reasoning on the kind of stream they dedupe in salary reports.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array nums, remove duplicates in place such that each unique element appears only once and return the new length. Do not allocate extra space for another array.
Constraints
1 <= nums.length <= 3*10^4-100 <= nums[i] <= 100nums is sorted non-decreasing
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 + rewrite
Push to a Set then rewrite nums in place.
- Time
- O(n)
- Space
- O(n)
const set = new Set(nums);
let i=0;
for (const v of set) nums[i++] = v;
return set.size;Tradeoff:
2. Two pointers
Slow pointer writes uniques; fast pointer scans.
- 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:
Glassdoor-specific tips
Glassdoor grades for the explicit O(1)-space contract — they dedupe billions of review tuples in stream pipelines and want candidates who naturally reach for in-place writes.
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 Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →