4. Remove Duplicates from Sorted Array
easyAsked at RobloxRemove duplicates from a sorted array in-place and return the new length.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array nums, remove duplicates in-place such that each unique element appears only once. Return the count k of unique elements; the first k slots of nums must contain those elements in order.
Constraints
1 <= nums.length <= 3 * 10^4nums is sorted in non-decreasing order
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 then refill
Use a Set to dedupe then write 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 pointers
Slow pointer marks write index, fast pointer scans. Advance slow only on a new value.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
if (!nums.length) return 0;
let slow = 0;
for (let fast = 1; fast < nums.length; fast++) {
if (nums[fast] !== nums[slow]) {
slow++;
nums[slow] = nums[fast];
}
}
return slow + 1;
}Tradeoff:
Roblox-specific tips
Roblox values in-place edits — keeping a single buffer matters when you are compacting a player's inventory snapshot on a memory-constrained server.
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 Roblox interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →