datarekha
Coding Patterns Easy Asked at AmazonAsked at GoogleAsked at Meta

How do you remove duplicates from a sorted array in place?

The short answer

Use a slow pointer that tracks where the next unique value should be written, and a fast pointer that scans forward. Whenever the fast pointer finds a value different from the current unique one, copy it to the slow pointer's position and advance both. One pass, O(1) extra space.

How to think about it

Recognise the pattern

The signal is sorted array + “in place” + “no extra space”. When you see those three words together, think slow-fast two-pointer (also called the read/write pointer pattern). One pointer defines the “write head” (where the next valid value goes), and the other scans ahead looking for the next valid value to copy in.

Build the approach step by step

Brute force would be to build a new list of unique values, then copy it back. That’s O(n) time but O(n) space — and it defeats the “in place” requirement.

The insight: because the array is sorted, all duplicates of a value sit next to each other. You only need to detect a change from one value to the next. Keep a write pointer w starting at index 1 (the first element is always unique). Walk a read pointer r from index 1 to the end. Every time nums[r] != nums[r-1], you’ve hit a new unique value — write it at w and increment w.

Walk through [1, 1, 2, 3, 3, 4]:

r=1: nums[1]==nums[0] (1==1) → skip
r=2: nums[2]!=nums[1] (2!=1) → write nums[2] at w=1, w becomes 2
r=3: nums[3]!=nums[2] (3!=2) → write at w=2, w becomes 3
r=4: nums[4]==nums[3] (3==3) → skip
r=5: nums[5]!=nums[4] (4!=3) → write at w=3, w becomes 4

Result: array starts with [1, 2, 3, 4, ...], return w=4.

Complexity

  • Time — O(n): the read pointer visits every element exactly once.
  • Space — O(1): the write pointer and loop variable are the only extras.

The trap and a pointer diagram

Keep practising

All Coding Patterns questions

Explore further

Skip to content