Problem 80

Abstract / Summary

Modify a sorted array in place so that each value appears at most twice and return the new length.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
25 lines | 670 bytes | submitted August 18, 2023 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.59 | σ = 1.45

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
55 links | 38 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Remove Duplicates from Sorted Array II - Leetcode 80 - Python'
NeetCodeIO 13 mins
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
YouTube video 'Remove Duplicates from Sorted Array II | leetcode 80 | two pointer'
Naresh Gupta 6 mins
Remove Duplicates from Sorted Array II | leetcode 80 | two pointer
YouTube video 'Remove Duplicates from Sorted Array II - Leetcode'
Aryan Mittal 9 mins
Remove Duplicates from Sorted Array II - Leetcode
YouTube video 'Remove Duplicates From Sorted Array II | Leetcode 80 | Live Coding session | December Challenge'
Coding Decoded 10 mins
Remove Duplicates From Sorted Array II | Leetcode 80 | Live Coding session | December Challenge
YouTube video '80. Remove Duplicates from Sorted Array II | LEETCODE MEDIUM | INTERVIEW PROBLEM'
code Explainer 7 mins
80. Remove Duplicates from Sorted Array II | LEETCODE MEDIUM | INTERVIEW PROBLEM
YouTube video 'Leetcode|Top Interview 150 |Medium|80. Remove Duplicates from Sorted Array II |Time: O(N)|Javascript'
Software Interviews Prep 15 mins
Leetcode|Top Interview 150 |Medium|80. Remove Duplicates from Sorted Array II |Time: O(N)|Javascript
YouTube video 'LeetCode 80. [Medium] Remove Duplicates from Sorted Array II'
Francesco Manicardi 4 mins
LeetCode 80. [Medium] Remove Duplicates from Sorted Array II
YouTube video 'Daily Leetcode #255: Dec 11, 2020 - 80. Remove Duplicates from Sorted Array II'
Programming Live with Larry 9 mins
Daily Leetcode #255: Dec 11, 2020 - 80. Remove Duplicates from Sorted Array II
YouTube video 'LeetCode 80 | Remove Duplicates from Sorted Array II | 2 Pointers | Java'
Sleepy Cracker 3 mins
LeetCode 80 | Remove Duplicates from Sorted Array II | 2 Pointers | Java
YouTube video 'LeetCode 80 | Remove Duplicates from Sorted Array II | Array | Java'
Sleepy Cracker 4 mins
LeetCode 80 | Remove Duplicates from Sorted Array II | Array | Java
YouTube video 'Daily Leetcode #677: Feb 06, 2022 - 80. Remove Duplicates from Sorted Array II'
Programming Live with Larry 14 mins
Daily Leetcode #677: Feb 06, 2022 - 80. Remove Duplicates from Sorted Array II
YouTube video 'Leetcode Question 80 "Remove Duplicates from Sorted Array II" in Javascript'
Ghumman Tech 4 mins
Leetcode Question 80 "Remove Duplicates from Sorted Array II" in Javascript
YouTube video 'Leetcode 80  Remove Duplicates from Sorted Array II'
AlgorithmicIQ 15 mins
Leetcode 80 Remove Duplicates from Sorted Array II
YouTube video '80. Remove Duplicates from Sorted Array II |Overwriting Unwanted Duplicates|Top Interview|LEETCODE'
Software Interviews Prep 9 mins
80. Remove Duplicates from Sorted Array II |Overwriting Unwanted Duplicates|Top Interview|LEETCODE
YouTube video '80. Remove Duplicates from Sorted Array II | Popping Unwanted Duplicates| Top Interview 150|LEETCODE'
Software Interviews Prep 8 mins
80. Remove Duplicates from Sorted Array II | Popping Unwanted Duplicates| Top Interview 150|LEETCODE
YouTube video '80. Remove Duplicates from Sorted Array II (LeetCode)'
hakunamatasq 3 mins
80. Remove Duplicates from Sorted Array II (LeetCode)
YouTube video 'LeetCode 80 | Remove Duplicates From Sorted Array II'
TickQ 4 mins
LeetCode 80 | Remove Duplicates From Sorted Array II
17 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 easy 6 medium 2 hard
13 solutions   August 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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