LeetCode 80: Remove Duplicates from Sorted Array II — Python Solution

LeetCode 80: Remove Duplicates from Sorted Array II is a Medium array / string problem. This Python walkthrough develops a bounded write pointer solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patternbounded write pointer
ComplexityO(n) time and O(1) extra space

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, allow a value when fewer than two values have been written or when it differs from the value two output positions back. The invariant worth writing beside the code is: No value occurs more than twice in the written prefix, and every permitted occurrence is retained.

Step-by-step algorithm

  1. Identify the input state consumed by removeDuplicates(nums) and initialize the data required by the bounded write pointer pattern.
  2. Allow a value when fewer than two values have been written or when it differs from the value two output positions back.
  3. After each update, verify the page’s central invariant: No value occurs more than twice in the written prefix, and every permitted occurrence is retained.
  4. Finish only after the boundary behavior is covered: Short arrays need no special rewriting; long duplicate runs collapse to two values.

Python solution

class Solution:
    def removeDuplicates(self, nums):
        write = 0
        for value in nums:
            if write < 2 or value != nums[write - 2]:
                nums[write] = value
                write += 1
        return write

Reading the implementation

The main entry point is removeDuplicates(nums). The named working state includes write; those variables make the bounded write pointer state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, allow a value when fewer than two values have been written or when it differs from the value two output positions back.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Allow a value when fewer than two values have been written or when it differs from the value two output positions back. Each update records the current item without invalidating earlier decisions; consequently, no value occurs more than twice in the written prefix, and every permitted occurrence is retained.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

nums=[0,0,1,1,1,1,2,3,3]; k=Solution().removeDuplicates(nums); assert nums[:k] == [0,0,1,1,2,3,3]

Common mistakes and edge cases

  • Problem-specific boundary: Short arrays need no special rewriting; long duplicate runs collapse to two values.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that no value occurs more than twice in the written prefix, and every permitted occurrence is retained.

Interview review checklist

  • Explain why bounded write pointer matches the structure of this input.
  • State the invariant in one sentence before tracing code: No value occurs more than twice in the written prefix, and every permitted occurrence is retained.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: Short arrays need no special rewriting; long duplicate runs collapse to two values.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 26. Remove Duplicates from Sorted Array · Next: 169. Majority Element