4. Remove Duplicates from Sorted Array
easyAsked at SwiggyCompact a sorted array in-place so each value appears once, returning the new length.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array nums, remove duplicates in-place so that each unique element appears only once. Return the count k of unique elements. The first k positions of nums must hold those values in order.
Constraints
1 <= nums.length <= 3 * 10^4Array is sorted non-decreasingMust modify in-place with O(1) extra memory
Examples
Example 1
nums=[1,1,2]k=2, nums=[1,2,_]Example 2
nums=[0,0,1,1,1,2,2,3,3,4]k=5, nums=[0,1,2,3,4,_,_,_,_,_]Approaches
1. Set copy back
Dedup via Set then overwrite.
- 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 in-place
Write pointer advances only when current value differs from the last written value. Read pointer scans every element.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let write = 1;
for (let read = 1; read < nums.length; read++) {
if (nums[read] !== nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}Tradeoff:
Swiggy-specific tips
Swiggy uses this warm-up to test in-place mutation discipline before moving into courier-route compaction problems where memory pressure matters on edge devices.
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 Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →