In this Leetcode Move Zeroes problem solution we have given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Leetcode Move Zeroes problem solution


Problem solution in Python.

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)):
            if(nums[i]==0):
                nums.remove(nums[i])
                nums.append(0)
            else:
                continue



Problem solution in Java.

class Solution {
    public void moveZeroes(int[] nums) {
        int idx = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[idx] = nums[i];
                idx++;
            }
        }
        for (; idx < nums.length; idx++) {
            nums[idx] = 0;
        }
    }
}


Problem solution in C++.

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        
        int n = nums.size();
        int l = 0, r = 0;
       while(r < n && l < n) {
           while(l < n - 1 && nums[l] != 0) {
               ++l;
           }
            while(r < n- 1 && (r <= l || nums[r] == 0)) {
               ++r;
           }
           swap(nums[l++], nums[r++]);
       }
    }
};


Problem solution in C.

void moveZeroes(int* nums, int numsSize){
    int p1 = 0, p2 = 0;
    
    while(p2 < numsSize){
        while(p2 < numsSize && nums[p2] == 0) p2++;
        if(p2 < numsSize && p1 < p2){
            nums[p1] = nums[p2];
            nums[p2] = 0;
        }
        p1++;
        p2++;
    }
}