Move Zeroes LeetCode

Beats 97% of leetcode submissions
Quoestion: ClickHere
Approach: intialize a counter to 0  we traverse through array and check if element is equal to zero or not.if element is not zero add element to array at counter index and increase counter.After traversing the array add zeros to array from index counter to lenght of arr -1:

Python Code:
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        pos = 0
        for i in nums:
            if i!=0:
                nums[pos] = i
                pos+=1
        for i in range(pos,len(nums)):
            nums[i] = 0
        

Post a Comment

0 Comments