HomeLeetcode283. Move Zeroes - Leetcode Solutions

283. Move Zeroes – Leetcode Solutions

Description

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.

Examples:

Example 1:

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

Example 2:

Input: nums = [0]
Output: [0]

Solution in Python

Python
from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Moves all 0's to the end of the input list 'nums', while maintaining the relative order 
        of the non-zero elements. The operation is done in-place without making a copy of the array.
        
        :param nums: List of integers
        :return: None (modifies the input list in-place)
        """
        
        # Pointer to track the position of the next non-zero element
        non_zero_index = 0
        
        # Iterate through the list
        for i in range(len(nums)):
            # If the current element is non-zero, we swap it with the element at the non_zero_index
            if nums[i] != 0:
                # Swap the current element with the element at the non_zero_index
                nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index]
                # Increment the non_zero_index after placing a non-zero element
                non_zero_index += 1

Explanation:

  • non_zero_index: This pointer keeps track of the position where the next non-zero element should be placed. It starts at the beginning of the list.
  • Main loop: The loop iterates through each element of the list. Whenever it encounters a non-zero element, it swaps it with the element at non_zero_index. Then, the non_zero_index is incremented.
  • Effect of the swap: After all iterations, all non-zero elements will have been moved to the start of the list in their original order, and the remaining positions will automatically hold the zeros.

Solution in C++

C++
#include <vector>
using namespace std;

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        // Pointer to keep track of the position where the next non-zero element should be placed
        int nonZeroIndex = 0;
        
        // Iterate through the vector
        for (int i = 0; i < nums.size(); i++) {
            // If the current element is non-zero, move it to the position tracked by nonZeroIndex
            if (nums[i] != 0) {
                // Swap the current element with the element at nonZeroIndex
                swap(nums[nonZeroIndex], nums[i]);
                // Increment the nonZeroIndex to the next position
                nonZeroIndex++;
            }
        }
    }
};

Solution in Javascript

JavaScript
var moveZeroes = function(nums) {
    // Initialize a pointer to keep track of the position to place the next non-zero element
    let nonZeroIndex = 0;
    
    // Iterate through the array using a for loop
    for (let i = 0; i < nums.length; i++) {
        // Check if the current element is non-zero
        if (nums[i] !== 0) {
            // If it's non-zero, swap it with the element at nonZeroIndex
            [nums[nonZeroIndex], nums[i]] = [nums[i], nums[nonZeroIndex]];
            // Increment the nonZeroIndex to the next position
            nonZeroIndex++;
        }
    }
};

Solution in Java

Java
class Solution {
    public void moveZeroes(int[] nums) {
        // Initialize a pointer to keep track of the position for the next non-zero element
        int nonZeroIndex = 0;

        // Iterate through the array
        for (int i = 0; i < nums.length; i++) {
            // If the current element is non-zero
            if (nums[i] != 0) {
                // Swap the current element with the element at nonZeroIndex
                int temp = nums[nonZeroIndex]; // Store the current value at nonZeroIndex
                nums[nonZeroIndex] = nums[i];  // Move the non-zero element to nonZeroIndex
                nums[i] = temp;                 // Place the original non-zero element in the current position
                // Increment the nonZeroIndex to the next position
                nonZeroIndex++;
            }
        }
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular