4. Remove Duplicates from Sorted Array
easyAsked at LINEDedup a sorted array in place — LINE uses this when discussing how to compact dedup'd message IDs in an offline outbox.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted array nums, remove duplicates in place so each element appears only once and return the new length. Modify the array in place with O(1) extra memory.
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. Use a Set then copy back
Build a Set, sort entries, and copy them back into the array.
- 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
Track a write index that only advances when the current value differs from the previous kept value.
- 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:
LINE-specific tips
Tie the in-place trick to mobile memory pressure — LINE clients run on low-end Android in Indonesia and Thailand, so allocator-free passes matter.
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 LINE interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →