↓Skip to main content
  1. LeetCode/

LeetCode 80: Remove Duplicates from Sorted Array II

·1 min· ·
LeetCode Medium Array Two-Pointers
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-26

  • Submissions: Wrong Answer ×3 → Runtime Error → Accepted ×4

Approach
#

The same write pointer as LC 26 (Two Pointers Template 5), allowing two copies. A number x may be written when k < 2 or x != nums[k - 2]; equal to the one two slots back means two copies are already written.

My Attempts
#

The early versions tracked occurrences with a counter c and complicated updates for two pointers i and j: [0, 0, 0] returned 3 instead of 2, and a single element returned 0.

Solution
#

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 0
        for x in nums:
            if k < 2 or x != nums[k - 2]:
                nums[k] = x
                k += 1
        return k

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Compare with the already written nums[k - 2], not the original nums[i - 2] (which may be overwritten).

Interview Explanation
#

With at most two copies, a write pointer accepts a number only when it differs from the value two slots back; for at most m copies just replace 2 with m. Time O(n).

Related

LeetCode 75: Sort Colors
·2 mins
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 note: the Dutch flag, with 0s left of low and 2s right of high; after swapping a 2 to high, do not advance, since the swapped-in value is unchecked
LeetCode 31: Next Permutation
·2 mins
LeetCode Medium Array Two-Pointers
LeetCode 31 note: from the right find the first dip i, swap it with the smallest larger value to its right, then reverse everything after i, with comparisons that include equality
LeetCode 11: Container With Most Water
·2 mins
LeetCode Medium Array Two-Pointers Greedy
LeetCode 11 note: start pointers at both ends and always move the shorter side; moving the taller side only narrows the width without raising the height
LeetCode 15: 3Sum
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 15 note: sort, fix the first number, and find the other two with converging pointers, skipping equal values at all three positions to avoid duplicate triplets
LeetCode 16: 3Sum Closest
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 16 note: sort, fix one number, and find the other two with converging pointers, comparing the distance abs(sum - target)
LeetCode 18: 4Sum
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 18 note: sort, fix the first two numbers with two loops, and converge pointers for the rest, skipping equal values at all four positions