Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Electronic Arts

In-place dedup of a sorted array using two pointers — a classic systems-style array problem.

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

Problem

Given a sorted array nums, remove duplicates in place so each unique element appears only once. Return the number of unique elements; the first k slots of nums must contain the unique values.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order

Examples

Example 1

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

Example 2

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

Approaches

1. Set + rewrite

Push uniques into a Set, then rewrite the array prefix.

Time
O(n)
Space
O(n)
const s=[...new Set(nums)];
for(let i=0;i<s.length;i++) nums[i]=s[i];
return s.length;

Tradeoff:

2. Two pointers

Maintain a write index; advance it only when the read value differs from the previous unique.

Time
O(n)
Space
O(1)
function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let k = 1;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] !== nums[k - 1]) {
      nums[k] = nums[i];
      k++;
    }
  }
  return k;
}

Tradeoff:

Electronic Arts-specific tips

EA emphasizes in-place allocation discipline — gameplay code paths can't afford GC churn, so prefer the O(1)-space pointer pass.

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

Practice these live with InterviewChamp.AI →