Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Indeed

Compact a sorted array in place so each unique value appears once — Indeed's dedup warmup before scaling to duplicate job-posting suppression.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a sorted array nums, remove duplicates in place such that each element appears only once and return the new length. Modify the input array directly without using extra space.

Constraints

  • 1 <= nums.length <= 3*10^4
  • -100 <= nums[i] <= 100
  • nums is sorted ascending

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. Set rewrite

Push into a Set then write back.

Time
O(n)
Space
O(n)
const set = new Set(nums);
let i = 0;
for (const v of set) nums[i++] = v;
return set.size;

Tradeoff:

2. Two pointers

Slow pointer marks next write slot; fast pointer scans for new values.

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:

Indeed-specific tips

Indeed maps this directly to dedup on canonicalized job postings — bonus signal if you describe how the two-pointer pass mirrors a single-stream dedup over a sorted hash-of-posting stream.

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 Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →