80/670

80. Remove Duplicates from Sorted Array II

Medium

You receive an integer array nums sorted in non-decreasing order. Compact it in place so that every distinct value keeps at most two occurrences, with the survivors staying in sorted order at the front of the array, and return k, the number of elements kept.

After your function finishes, the first k slots of nums must hold the compacted sequence; whatever remains past index k - 1 is ignored. The intended solution overwrites as it scans, using O(1) extra memory rather than building a second array.

Example 1:

Input: nums = [1, 1, 1, 2, 2, 3]

Output: k = 5, nums → [1, 1, 2, 2, 3]

Explanation: The third 1 is dropped; every value now appears at most twice, so k = 5.

Example 2:

Input: nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]

Output: k = 7, nums → [0, 0, 1, 1, 2, 3, 3]

Explanation: The four 1s shrink to two; 0, 2, and 3 already fit the limit, so k = 7.

Constraints:

  • 1 ≤ nums.length ≤ 3 * 10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • nums is sorted in non-decreasing order

Hints:

Sorted input means equal values sit side by side — so an element is a third-or-later copy exactly when it matches the value two positions earlier in the kept prefix.

Keep a write pointer w over the same array: for each element x, copy it to nums[w] and advance w unless w >= 2 and nums[w - 2] == x. The kept prefix never outruns the read position, so nothing is overwritten too early. Return w.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 1, 1, 2, 2, 3]

Expected output: k = 5, nums → [1, 1, 2, 2, 3]