4. Remove Duplicates from Sorted Array
easyAsked at GitHubRemove duplicates in-place from a sorted array — GitHub uses this as the entry-level analogue to dedup-ing sorted SHA streams in the packfile delta index.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums sorted in non-decreasing order, remove duplicates in-place such that each unique element appears only once. Return the number of unique elements.
Constraints
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100nums is sorted
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. Brute force
Use a Set, rebuild array.
- Time
- O(n)
- Space
- O(n)
const set = new Set(nums);
const arr = [...set];
for (let i=0;i<arr.length;i++) nums[i]=arr[i];
return arr.length;Tradeoff:
2. Two-pointer in-place
Maintain a write pointer; advance it only when the current value differs from the last written value. O(1) extra space exploits the sorted invariant.
- 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[read - 1]) {
nums[write++] = nums[read];
}
}
return write;
}Tradeoff:
GitHub-specific tips
GitHub grades whether you exploit the sorted invariant — the same trick used in pack-index binary search over sorted SHAs.
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 GitHub interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →