4. Remove Duplicates from Sorted Array
easyAsked at EtsyCompact a sorted array in-place — Etsy uses it to check whether you write O(1)-space code without leaning on a Set.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums sorted in non-decreasing order, remove duplicates in-place so that each unique element appears once. Return the new length k; the first k elements of nums must hold the unique values in original order.
Constraints
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100nums is sorted ascending
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. Use a Set
Copy unique values into a Set, then back into the array.
- 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 pointers
Keep a write pointer that advances only on new values.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (!nums.length) return 0;
let w = 1;
for (let r = 1; r < nums.length; r++) {
if (nums[r] !== nums[r-1]) nums[w++] = nums[r];
}
return w;
}Tradeoff:
Etsy-specific tips
Etsy interviewers grade on whether you mutate in-place — they're alert to candidates who'd waste memory deduping recommended-listing arrays at scale.
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 Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →