#80

Remove Duplicates from Sorted Array II

Medium Read/write pointers

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

?The problem

In a sorted array, keep at most two copies of each value at the front, in place, and return the new length.

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

◎Understanding

Really asking: keep at most two copies of each value.

Why this works: a value may be written if it differs from the value two places behind the write pointer.

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

write 1, 1third 1 = nums[write-2] → skipwrite 2, 2, 3 → [1, 1, 2, 2, 3]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Comparing with nums[read - 2] instead of nums[write - 2] — the read side still contains the extra copies.