#26

Remove Duplicates from Sorted Array

Easy Read/write pointers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a sorted array, keep only one copy of each value at the front (in order) and return how many unique values there are. Do it in place.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: keep one copy of each value at the front, in place, and return how many unique values there are.

Why this works: in a sorted array duplicates are neighbours. The read pointer scans; the write pointer only moves when a new value appears.

Example: [1, 1, 2, 3, 3]

read 1 (dup) → skipread 2 → write at 1 → [1, 2, …]read 3 → write at 2 → [1, 2, 3, …]read 3 (dup) → skip; length 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Comparing nums[read] with nums[read - 1] after you've started overwriting — compare with nums[write - 1] to be safe.