InterviewPrepKit

Home / Coding / Two Pointers

Remove Duplicates from Sorted Array

easy Original β†—
Solving tips
  • Because the array is sorted, duplicates are adjacent, so 'is this new?' is one comparison against the last kept value nums[write-1].
  • Slow/fast pointers: write marks the deduped prefix length (start at 1), read scans; copy nums[read] down only when it differs, then bump write.
  • Return k (the count), not the array; the tail beyond index k-1 is deliberately ignored by the judge.
  • O(n) time, O(1) space; don't use del/remove in a loop (O(n^2)), and the nums[write-K] comparison generalizes to the at-most-K-duplicates variant.

Problem

You are given an integer array nums sorted in non-decreasing order. Rearrange it in place so that each distinct value appears exactly once, keeping the distinct values in their original (sorted) order. Return k, the number of distinct values.

Only the first k slots of nums matter afterward β€” the judge reads nums[0..k-1] and compares against the expected distinct values; whatever sits beyond index k - 1 is ignored. You may not allocate a second array (O(1) extra memory required).

Examples

  • nums = [1,1,2] β†’ k = 2, nums starts with [1,2] Two distinct values; the duplicate 1 is squeezed out.
  • nums = [0,0,1,1,1,2,2,3,3,4] β†’ k = 5, nums starts with [0,1,2,3,4] Five distinct values survive, still in ascending order.
  • nums = [7] β†’ k = 1, nums starts with [7] A single element is trivially duplicate-free.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.
  • O(1) extra memory β€” expected O(n) time.

Think about it first

Hint 1 Because the array is sorted, all copies of a value sit next to each other. A value is a duplicate exactly when it equals its left neighbor.
Hint 2 Use one pointer to scan every element and another to mark where the next *new* value should be written. When do the two pointers move together, and when does only one move?
Hint 3 Keep `write` = length of the deduplicated prefix built so far. Scan with `read`; whenever `nums[read] != nums[write - 1]` (a value you haven't kept yet), copy it to `nums[write]` and bump `write`. Return `write`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.