Remove Element in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array num and another value val, we have to remove all instances of that value in-place and find the new length.

So, if the input is like [0,1,5,5,3,0,4,5] 5, then the output will be 5.

To solve this, we will follow these steps −

  • count := 0

  • for each index i of nums

    • if nums[i] is not equal to val, then −

      • nums[count] := nums[i]

    • count := count + 1

  • return count

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def removeElement(self, nums, val):
      count = 0
      for i in range(len(nums)):
         if nums[i] != val :
            nums[count] = nums[i]
            count +=1
      return count
ob = Solution()
print(ob.removeElement([0,1,5,5,3,0,4,5], 5))

Input

[0,1,5,5,3,0,4,5], 5

Output

5
raja
Published on 10-Jun-2020 12:02:34
Advertisements