Remove Duplicates from Sorted Array II

medium

Remove duplicates allowing at most two of each element

Remove Duplicates from Sorted Array II

Key Insight

Compare nums[fast] with nums[slow-2]. If different, it is safe to keep — allows at most 2 of each value.

Step 1Setup
First 2 always kept
1
0
1
1
slow
fast
1
2
2
3
2
4
3
5
same direction

Allow at most 2 of each value. slow=2, fast=2. First 2 elements always kept.

1 / 6

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Remove Duplicates from Sorted Array II

Compare nums[fast] with nums[slow-2]. If different, it is safe to keep — allows at most 2 of each value.

  1. Setup

    Allow at most 2 of each value. slow=2, fast=2. First 2 elements always kept.

  2. Third Duplicate

    fast=2: nums[2]=1, nums[slow-2]=nums[0]=1. Same! Skip third 1.

  3. New Value

    fast=3: nums[3]=2, nums[slow-2]=nums[0]=1. Different! Copy 2 to slow.

  4. Second Copy

    fast=4: nums[4]=2, nums[slow-2]=nums[1]=1. Different! Copy 2.

  5. Last Value

    fast=5: nums[5]=3, nums[slow-2]=nums[2]=2. Different! Copy 3.

  6. Result

    Length 5. Array contains [1,1,2,2,3] — at most 2 of each.