Skip to content

Remove Duplicates from Sorted Array II

Given an integer array nums sorted in non-decreasing order, modify it in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Then return the number of elements k.

Consider the number of elements of nums to be k. To get accepted, you need to do the following things:

  1. Change the array nums such that the first k elements of nums contain the elements which appear at most twice.
  2. The remaining elements of nums are not important as well as the size of nums.
  3. Return k.
InputOutputExplanation
[1, 1, 1, 2, 2, 3]5Array becomes [1, 1, 2, 2, 3, _]. First 5 elements allow duplicates up to 2.
[0, 0, 1, 1, 1, 1, 2, 3, 3]7Array becomes [0, 0, 1, 1, 2, 3, 3, _, _]. Each unique value appears at most twice.
  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.
ApproachTimeSpaceModifies ArrayBest When
Two Pointers with CounterO(n)O(1)YesTracking duplicate count explicitly — most intuitive
Simple Two PointersO(n)O(1)YesCompact solution — no explicit counter variable
  • Pick Two Pointers with Counter if you want explicit, easy-to-understand logic.
  • Pick Simple Two Pointers if you prefer compact, clever indexing without a counter.
Intuitive
Two Pointers with Counter
O(n) time · O(1) space
Compact
Simple Two Pointers
O(n) time · O(1) space
★ Recommended

Use two pointers and track the count of consecutive equal elements. Write an element to the result position if:

  1. It’s the first element, or
  2. It’s different from the previous element, or
  3. It’s the same as the previous but we’ve only seen it once so far (count < 2)

The counter resets when we encounter a new element.

⏱ Time O(n) Single pass 💾 Space O(1) No extra space

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

Stepinums[i]countSame as prev?count < 2?ActionkArray State
Start-----Initialize0[1, 1, 1, 2, 2, 3]
1011--First element, write1[1, 1, 1, 2, 2, 3]
2112YesYesWrite (count < 2)2[1, 1, 1, 2, 2, 3]
3212YesNoSkip (count = 2)2[1, 1, 1, 2, 2, 3]
4321No-New element, write3[1, 1, 2, 2, 2, 3]
5422YesYesWrite (count < 2)4[1, 1, 2, 2, 2, 3]
6531No-New element, write5[1, 1, 2, 2, 3, 3]

Return k = 5, array first 5 elements: [1, 1, 2, 2, 3]

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

Stepinums[i]ActionkProgress
Start--Initialize0Start with k=0
100First element, write, count=11[0, ...]
210Same, count < 2, write, count=22[0, 0, ...]
321New element, write, count=13[0, 0, 1, ...]
431Same, count < 2, write, count=24[0, 0, 1, 1, ...]
541Same, count = 2, skip4No change
651Same, count = 2, skip4No change
762New element, write, count=15[0, 0, 1, 1, 2, ...]
873New element, write, count=16[0, 0, 1, 1, 2, 3, ...]
983Same, count < 2, write, count=27[0, 0, 1, 1, 2, 3, 3, ...]

Return k = 7

Animated walkthrough

How the counter approach handles duplicates up to 2

Watch the counter track consecutive occurrences. When count reaches 2, we skip further duplicates. A new element resets the counter.

Step 1 of 3
Waiting to begin...
Array state
Memory / lookup state

function removeDuplicates(nums):
if nums is empty:
return 0
k = 1
count = 1
for i from 1 to len(nums) - 1:
if nums[i] != nums[i - 1]:
count = 1
nums[k] = nums[i]
k = k + 1
else if count < 2:
count = count + 1
nums[k] = nums[i]
k = k + 1
return k
remove_duplicates_from_sorted_array_ii_counter.py
from typing import List
def removeDuplicates(nums: List[int]) -> int:
"""
Two Pointers with Counter Approach
Allow each element to appear at most twice using explicit count tracking.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if not nums:
return 0
k = 1
count = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
# New element encountered, reset counter
count = 1
nums[k] = nums[i]
k += 1
elif count < 2:
# Same element but less than 2 occurrences, allow it
count += 1
nums[k] = nums[i]
k += 1
# else: count == 2, skip this duplicate
return k
# Test cases
print(removeDuplicates([1, 1, 1, 2, 2, 3])) # 5, nums = [1, 1, 2, 2, 3, _]
print(removeDuplicates([0, 0, 1, 1, 1, 1, 2, 3, 3])) # 7, nums = [0, 0, 1, 1, 2, 3, 3, _, _]
print(removeDuplicates([1])) # 1, nums = [1]
print(removeDuplicates([1, 2])) # 2, nums = [1, 2]
✓ Simple

Instead of explicitly tracking a counter, use a clever indexing technique: only write an element if it differs from the element 2 positions before it (if it exists). This implicitly ensures at most 2 occurrences.

The key insight: nums[k - 2] is the element from 2 positions back in the result. If the current element is different from it, we can safely add it (ensuring at most 2 occurrences of any value).

⏱ Time O(n) Single pass 💾 Space O(1) No extra space

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

Stepknums[k-2]nums[i]Different?ActionResult
Start0---Initialize-
11-1AlwaysWrite first element[1, ...]
22-1AlwaysWrite second element[1, 1, ...]
3211NoSkip (already 2)No change
4312YesWrite[1, 1, 2, ...]
5412YesWrite[1, 1, 2, 2, ...]
6523YesWrite[1, 1, 2, 2, 3, ...]

Return k = 5

function removeDuplicates(nums):
if nums is empty:
return 0
k = 0
for i from 0 to len(nums) - 1:
if k < 2 or nums[i] != nums[k - 2]:
nums[k] = nums[i]
k = k + 1
return k

The condition k < 2 or nums[i] != nums[k - 2] means:

  • Always write the first 2 elements (k < 2)
  • For elements beyond that, write only if they differ from the element 2 positions back (nums[i] != nums[k - 2])
remove_duplicates_from_sorted_array_ii_simple.py
from typing import List
def removeDuplicates(nums: List[int]) -> int:
"""
Simple Two Pointers Approach
Allow at most 2 occurrences by checking if current element differs from element 2 positions back.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if not nums:
return 0
k = 0
for i in range(len(nums)):
# Always write first 2 elements, or if current differs from element 2 positions back
if k < 2 or nums[i] != nums[k - 2]:
nums[k] = nums[i]
k += 1
return k
# Test cases
print(removeDuplicates([1, 1, 1, 2, 2, 3])) # 5, nums = [1, 1, 2, 2, 3, _]
print(removeDuplicates([0, 0, 1, 1, 1, 1, 2, 3, 3])) # 7, nums = [0, 0, 1, 1, 2, 3, 3, _, _]
print(removeDuplicates([1])) # 1, nums = [1]
print(removeDuplicates([1, 2])) # 2, nums = [1, 2]
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
remove_duplicates_from_sorted_array_ii_optimized.py
"""
Solution for Remove Duplicates from Sorted Array II
"""
def solve():
"""Implementation for approach 3 of Remove Duplicates from Sorted Array II"""
pass
if __name__ == "__main__":
print("Solution ready")