Skip to content
Programming101
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programmingoneonone

Leetcode Move Zeroes problem solution

YASH PAL, 31 July 2024

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++;
    }
}

coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes