Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Baidu

Remove 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 the duplicates in-place so each unique element appears only once. Return the number of unique elements; the first k slots must hold the unique values.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • Array is sorted non-decreasing
  • Must be done in-place with O(1) extra space

Examples

Example 1

Input
nums = [1,1,2]
Output
2, nums = [1,2,_]

Example 2

Input
nums = [0,0,1,1,1,2,2,3,3,4]
Output
5, nums = [0,1,2,3,4,_,_,_,_,_]

Approaches

1. Brute force

Build a new array of unique values, then copy back.

Time
O(n)
Space
O(n)
const seen=new Set();const out=[];
for(const x of nums) if(!seen.has(x)){seen.add(x);out.push(x);}
for(let i=0;i<out.length;i++) nums[i]=out[i];
return out.length;

Tradeoff:

2. Two pointers

Write pointer trails read pointer; advance write only when value changes.

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:

Baidu-specific tips

Baidu uses this to gauge whether you instinctively avoid extra memory, since their index-shards must compact duplicates at scale without copying.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Remove Duplicates from Sorted Array and other Baidu interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →