➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Remove Elements

image image

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

I just solved this using array method pop()

My solve script is in the below link

Solve Script: link image

Another efficient way to solve this is using Two Pointer

def removeElement(nums, val):
  index = 0
  
  for i in range(len(nums)):
      if nums[i] != val:
        nums[index] = nums[i]
        index += 1
  
  return index

Leetcode Submission Script

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0

        while i < len(nums):
            if nums[i] == val:
                nums.pop(i)
            else:
                i += 1
        
        return len(nums)