Friedrich Ewald My Personal Website

Leetcode: Remove element

Given an array nums, delete all items that are equal to val. Return the total number of remaining items and perform the deletion in place. The solution looks as follows. Initially, k is set to the length of the list. If we remove one element we decrement k by one. The one thing here is that we advance the pointer i only if we don’t remove an element. This is due to the fact that the position of the following elements change if we delete an item from the array.

from typing import List


class Solution:
  def removeElement(self, nums: List[int], val: int) -> int:
    i = 0
    k = len(nums)
    while i < len(nums):
      if nums[i] == val:
        del nums[i]
        k -= 1
      else:
        i += 1
    return k
    


if __name__ == '__main__':
  s = Solution().removeElement
  print(s([3,2,2,3], 3), 2)


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.