4. Remove Duplicates from Sorted Array
easyAsked at CanvaCompact a sorted array in place by removing duplicates — Canva uses this to evaluate two-pointer reasoning relevant to deduping asset-IDs in a design.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted integer array nums, remove the duplicates in place such that each unique element appears only once. Return the number of unique elements k; the first k elements of nums should hold the result.
Constraints
1 <= nums.length <= 3 * 10^4nums is sorted non-decreasing
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 with Set
Copy to a Set, write back unique values.
- 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-pointer in place
Slow pointer marks next unique slot; fast pointer scans forward. Write only when distinct. O(1) extra space.
- Time
- O(n)
- Space
- O(1)
function removeDup(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:
Canva-specific tips
Canva interviewers care that you keep memory in-place when designs scale to thousands of objects, mirroring how their editor compresses element arrays.
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 Canva interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →