↓Skip to main content
  1. LeetCode/

LeetCode 27: Remove Element

·1 min· ·
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: 2022-05-11

  • Submissions: Wrong Answer → Accepted ×3

Approach
#

A write pointer k (Two Pointers Template 5): copy every value not equal to val to nums[k] and advance. The first k slots are what remains; order does not matter.

My Attempts
#

Attempt 1 compared v != nums (a number against the whole list), always true, so nothing was removed: [2], val = 2 returned 1.

Solution
#

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

Complexity
#

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

Mistakes to Avoid
#

  • Compare against val.

Interview Explanation
#

A write pointer copies values not equal to val to the front in order, and I return the count. Time O(n), space O(1).

Related

LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1
LeetCode 66: Plus One
·2 mins
LeetCode Easy Array Math
LeetCode 66 note: add one from the last digit, turning 9s into 0s while carrying, and prepend 1 when every digit was 9
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