4. Remove Duplicates from Sorted Array
easyAsked at TeslaIn-place dedupe a sorted array and return the new length.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array nums, remove duplicates in-place so each element appears once and return the number of unique elements. The first k positions must hold the unique values.
Constraints
1 <= nums.length <= 3 * 10^4Array 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. Set + rewrite
Dump into a Set, write back.
- Time
- O(n)
- Space
- O(n)
const u = [...new Set(nums)];
for (let i = 0; i < u.length; i++) nums[i] = u[i];
return u.length;Tradeoff:
2. Two-pointer in-place
Slow pointer marks the last unique slot; fast scans forward.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (!nums.length) 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:
Tesla-specific tips
Tesla cares deeply about in-place memory ops — extra allocation in a control loop can cost a frame of latency and miss a real-time deadline.
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 Tesla interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →