4. Remove Duplicates from Sorted Array
easyAsked at GitLabIn-place deduplicate a sorted array and return the new length.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums sorted in non-decreasing order, remove duplicates in-place so each unique element appears once. Return the new length k; the first k elements of nums must be the unique values in order.
Constraints
1 <= nums.length <= 3*10^4Must be O(1) extra space
Examples
Example 1
[1,1,2]2, nums=[1,2,_]Example 2
[0,0,1,1,1,2,2,3,3,4]5, nums=[0,1,2,3,4,...]Approaches
1. Set + rewrite
Use a Set then copy values 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 pointers
Slow pointer marks next unique slot; fast scans for new values.
- 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:
GitLab-specific tips
GitLab cares about in-place mutations because pipeline runners care about memory ceilings — call out the O(1) extra space budget explicitly.
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 GitLab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →