Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Dropbox

Compact a sorted array in place; Dropbox uses it to probe two-pointer fluency for dedup passes over chunk-hash manifests.

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

Problem

Given a sorted integer array, remove duplicates in place such that each unique element appears once. Return the count of unique elements; the first k positions must hold them.

Constraints

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

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

Convert to a Set, sort back into the array.

Time
O(n log 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-pointer write index

Maintain a write pointer k; advance it only when the current value differs from the previous unique. Linear in place.

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:

Dropbox-specific tips

Dropbox interviewers expect you to verbalize the invariant 'nums[0..k) is the unique prefix' before coding — they grade on invariant-stating, not just correctness.

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

Practice these live with InterviewChamp.AI →