4. Remove Duplicates from Sorted Array
easyAsked at UdemyDedupe a sorted array in place — Udemy uses this to gauge two-pointer hygiene before dedupe questions on course catalog imports.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array nums, remove duplicates in place so each unique element appears once. Return the count k of unique elements; the first k elements of nums must hold those uniques.
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. Extra set
Copy uniques into a Set, then write them back.
- 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-pointer in place
Keep a write pointer k. Advance read pointer i; when nums[i] differs from nums[k-1], write it forward.
- 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[k - 1]) nums[k++] = nums[i];
}
return k;
}Tradeoff:
Udemy-specific tips
Udemy interviewers will pivot to deduping repeat course uploads after a CSV import — show you can adapt the two-pointer pattern to record-level dedupe keys.
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 Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →