↓Skip to main content
  1. LeetCode/

LeetCode 26: Remove Duplicates from Sorted Array

·2 mins· ·
LeetCode Easy 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: easy First Attempt: 2020-01-30

  • Submissions: Compile Error → Output Limit Exceeded → Accepted → Runtime Error ×5 → Wrong Answer ×2 → Runtime Error → Wrong Answer → Accepted → Runtime Error → Wrong Answer → Runtime Error ×3 → Accepted ×2

Approach
#

Sorted, so duplicates are adjacent. Keep a write pointer k (Two Pointers Template 5): for each number, write it to nums[k] and advance only if it differs from the last written nums[k - 1]. Return k; the first k slots hold the distinct values.

My Attempts
#

This was among my first problems in 2020 and 2022, and most early errors came from misreading what was asked: returning a tuple or a new list, or computing k as the number of duplicates rather than the number kept. One later version had the wrong write condition and did not skip duplicates: [2, 2, 4] kept [2, 2].

Solution
#

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

Complexity
#

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

Mistakes to Avoid
#

  • Modify the array in place and return the length, not a new list.

Interview Explanation
#

With a sorted array, a write pointer copies a value forward only when it differs from the last written one, and I return the count written. Time O(n), space O(1).

Related

LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length
LeetCode 1: Two Sum
·2 mins
LeetCode Easy Array Hash-Table
LeetCode 1 note: store seen numbers in a hash map while scanning and look up target - x; checking before storing prevents using one element twice
LeetCode 9: Palindrome Number
·2 mins
LeetCode Easy Math
LeetCode 9 note: negatives are never palindromes; without strings, reverse the second half of the digits and compare it with the first half
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 7: Reverse Integer
·2 mins
LeetCode Medium Math
LeetCode 7 note: remember the sign, reverse the digits of the absolute value, and return 0 when the result leaves the signed 32-bit range