Leetcode- 283 . Move Zeros

admin
By -
0

Photo by Tai Bui on Unsplash

 

Question:

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.


Note that you must do this in-place without making a copy of the array.


Topics: Array , Two Pointers

Link : https://leetcode.com/problems/move-zeroes/description/

Solution:

  1. Pointer i: Keeps track of the position where the next non-zero element should go.

  2. Pointer j: Iterates over the entire array.

Plan:

  • Start with i = 0 and j = 0.

  • Traverse through the array:

    • Whenever nums[j] is non-zero, move it to position i, and then increment i.

    • Continue until you've gone through the entire array.

  • After this loop, all non-zero elements will be in their correct positions, and i will indicate where the 0s should start.


Solution Code:
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i = 0
        for j in range(len(nums)):
            if nums[j] != 0:
                nums[i], nums[j]= nums[j] ,nums[i]
                i = i  + 1
        return nums

Post a Comment

0Comments

Put Your Thought or Query Here

Post a Comment (0)