CA 13 - Move Zeros

 Move Zeroes

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.

Example 1:

    Input: nums = [0,1,0,3,12]

    Output: [1,3,12,0,0]

Example 2:

    Input: nums = [0]

    Output: [0]

CODE:

    Intuitive way of solving this problem is by assigning two array shuch that both contains non-zero values and zero values separately and then finally add them such that all the zeros fall at the end of the array. 


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        n = len(nums)
        nonzero = []
        zero =[]
        for i in nums:
            if i == 0:
                zero.append(0)
            else:
                nonzero.append(i)
        newnum = nonzero+zero
        for i in range(0,n):
            nums[i] = newnum[i]

       

     Here the new arrays take the extra spacing, thus to avoid this we will make no new array and do in place swapping with the help of two pointers and condition based on our question. We will place two pointers left and right, if we encounter a "0" we will move the right pointer, if we encounter a non-zero value we will replace it with the left pointer value (which points to zero) and then move both the left and right pointer.


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        l = 0
        r = 0
        while r < len(nums):
            if nums[r]:
                nums[l],nums[r] = nums[r],nums[l]
                l+=1
            r+=1


Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries