Remove Duplicates from Sorted Array II
LeetCode 80 · Medium · solution, intuition & step-by-step walkthrough
Keep nums[i] unless it equals nums[insert_index − 2].
This is how I solved Remove Duplicates from Sorted Array II (LeetCode 80), a medium problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Allow each value at most twice: compare the incoming element with the one two slots behind the write position. If they're equal, a third copy would appear, so skip it.
Approach
- 1
The first two elements are always kept; insert_index = 2.
- 2
For each later element, skip it if it matches nums[insert_index − 2].
- 3
Otherwise write it and advance.
- 4
Return insert_index.
How I solved it
Write pointer, look back twoPythonO(n) time · O(1) space
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
insert_index=2
for i in range(2,len(nums)):
if nums[i]==nums[insert_index-2]:
continue
nums[insert_index]=nums[i]
insert_index+=1
return insert_indexRemove Duplicates from Sorted Array II — FAQ
What is the intuition behind Remove Duplicates from Sorted Array II?
Allow each value at most twice: compare the incoming element with the one two slots behind the write position. If they're equal, a third copy would appear, so skip it.
How do you solve Remove Duplicates from Sorted Array II (LeetCode 80)?
1. The first two elements are always kept; insert_index = 2. 2. For each later element, skip it if it matches nums[insert_index − 2]. 3. Otherwise write it and advance. 4. Return insert_index.
What is the time and space complexity of Remove Duplicates from Sorted Array II?
Time: O(n). Space: O(1). (Accepted approach: Write pointer, look back two.)
What are common mistakes in Remove Duplicates from Sorted Array II?
Compare against the write area, not the read area — that's what limits copies to two.