loading

Remove Duplicates from Sorted Array II — Step-by-Step Visualization

mediumLeetCode #80ArrayTwo Pointers

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. Return k after placing the final result in the first k slots of nums.

Algorithm Pattern

Two Pointers

Key Idea

Allow at most 2 of each — check against nums[k-2] instead of nums[k-1].

Step-by-Step Approach

  1. Set k=2 (first 2 elements always kept)
  2. From i=2, if nums[i] != nums[k-2], copy nums[i] to nums[k], k++

Related Problems