Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at DigitalOcean

Compact a sorted array so each element appears once and return the new length — DigitalOcean tests this to evaluate in-place transforms that mirror dedupe steps in region-level billing aggregation.

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

Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements; the relative order of the elements should be kept the same.

Constraints

  • 1 <= nums.length <= 3*10^4
  • Sorted non-decreasing

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. New array copy

Push uniques to a fresh array, copy back.

Time
O(n)
Space
O(n)
const seen=new Set(),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];

Tradeoff:

2. Two pointers

Slow pointer marks write index; fast scans for new values.

Time
O(n)
Space
O(1)
function removeDuplicates(nums) {
  if (nums.length === 0) 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:

DigitalOcean-specific tips

DigitalOcean weighs in-place mutation heavily because billing dedupe runs in tight loops where allocation pressure hurts droplet-bill batch throughput.

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

Practice these live with InterviewChamp.AI →