Python 0080.py
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return None
if len(nums) <= 2:
return len(nums)
# pass 1: mark duplicates
REMOVE = 99999999
for i in range(2, len(nums)):
if nums[i] == nums[i - 1] and nums[i] == nums[i - 2]:
nums[i - 2] = REMOVE
# pass 2: remove them
skip = 0
i = 0
while i < len(nums):
while nums[i] == REMOVE:
i += 1
skip += 1
nums[i - skip] = nums[i]
i += 1
return len(nums) - skip
Difficulty
and has an acceptance rate of about 65% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “remove duplicates allowing at most two occurrences” problem by performing two linear traversals of the input list nums. The algorithm first marks elements that would cause a third consecutive duplicate, then compacts the list in-place by skipping the marked entries. The function returns the new logical length of the array after duplicates have been removed.
Early-exit handling
if not nums:
return None
if len(nums) <= 2:
return len(nums)
These two guard clauses address the edge conditions where the input is empty or already short enough that no removal is required. Returning None for an empty list signals that there is no meaningful length to report, while a length of two or less guarantees compliance with the “at most two copies” rule without further processing.
Pass 1 - marking excess duplicates
REMOVE = 99999999
for i in range(2, len(nums)):
if nums[i] == nums[i - 1] and nums[i] == nums[i - 2]:
nums[i - 2] = REMOVE
The loop starts at index 2, ensuring that there are always two preceding elements to compare. When three consecutive values are identical, the algorithm marks the earliest of the three (i-2) with a sentinel value (REMOVE). By marking the leftmost element of each offending triple, the code guarantees that only the first two occurrences of any value remain unmarked, regardless of how many times the value repeats consecutively. The sentinel is chosen to be a value that is unlikely to appear in normal input, allowing it to be distinguished unambiguously during the second pass.
Pass 2 - compacting the array
skip = 0
i = 0
while i < len(nums):
while nums[i] == REMOVE:
i += 1
skip += 1
nums[i - skip] = nums[i]
i += 1
Two indices drive this phase: i scans the original positions, while skip counts how many sentinel entries have been encountered so far. The inner loop advances i past any consecutive sentinel values, incrementing skip for each one. After bypassing the marked elements, the current unmarked value is written back to the position i - skip, effectively shifting it left by the number of removed entries encountered earlier. This in-place shift eliminates the need for auxiliary storage.
Edge-case coverage
The algorithm gracefully handles an empty list by returning None. When the list contains one or two elements, the early-exit clause returns the original length, avoiding unnecessary work. If the entire list consists of the same value repeated many times, the marking loop will flag every third element, and the compaction loop will collapse the array to exactly two copies of that value. The sentinel value approach also works when the list contains the sentinel itself as a legitimate element; in that rare scenario the sentinel would be indistinguishable from a genuine value, but the choice of a large constant makes such a collision highly improbable for typical integer inputs.
Performance-related observations
The two passes each traverse the list exactly once, resulting in linear time behavior. The marking phase does not modify elements other than the sentinel assignment, preserving the original order of the retained values. The compaction phase writes each unmarked element exactly once to its final location, avoiding repeated swaps or temporary buffers. By using a single integer sentinel rather than a separate boolean array, the implementation keeps auxiliary memory usage to a constant amount, regardless of input size. The combination of early exits for trivial inputs and the avoidance of extra data structures contributes to an efficient in-place solution.
ELI5 - Simplified Explanation
Imagine you have a long line of numbered building blocks. Some of these blocks look exactly the same, and there are way too many doubles. This code helps organize the blocks so there are never more than two of the same number in a row.
First, the code looks at the blocks to find any that are part of a group of three or more of the same number. When it finds those extra ones, it puts a special giant sticker on them that says they should be removed.
Next, the code starts fresh by sliding the good blocks forward to fill in any empty spaces. It walks down the line from start to finish, always moving the blocks that do not have the giant sticker over to the front of the line. By the time it reaches the end, all the good blocks are neatly gathered at the front, and the extra ones are pushed out of the way.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | C# | Rust | JS | Java | Go | TS | ||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| pruthvikp | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| pruthvikp | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 26: Remove Duplicates from Sorted Array
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 905: Sort Array By Parity
- problem 922: Sort Array By Parity II
- problem 2423: Remove Letter To Equalize Frequency
- problem 18: 4Sum
- problem 92: Reverse Linked List II
- problem 93: Restore IP Addresses
- problem 384: Shuffle an Array
- problem 1143: Longest Common Subsequence
- problem 1615: Maximal Network Rank
- problem 32: Longest Valid Parentheses
- problem 149: Max Points on a Line
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality