4. Remove Duplicates from Sorted Array
easyAsked at TripAdvisorRemove duplicates from a sorted array in-place so each element appears only once.
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. The relative order of the elements should be kept the same. Return the number of unique elements.
Constraints
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100nums is sorted in non-decreasing order
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 unique values to a set, then copy back.
- Time
- O(n)
- Space
- O(n)
const seen = new Set();
let k = 0;
for (const x of nums) {
if (!seen.has(x)) { nums[k++] = x; seen.add(x); }
}
return k;Tradeoff:
2. Two-pointer in place
Slow pointer marks write position, fast pointer scans. Exploits sortedness.
- 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:
TripAdvisor-specific tips
TripAdvisor uses this to test in-place mutation discipline when deduping review IDs in sorted batches.
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 TripAdvisor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →