Move Zeroes to the End of an Array

Problem

Move all zeroes in an array to the end, in place, while keeping the relative order of the non-zero elements.

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

Python Solution

def move_zeroes(nums):
    insert_pos = 0
    for num in nums:
        if num != 0:
            nums[insert_pos] = num
            insert_pos += 1
    for i in range(insert_pos, len(nums)):
        nums[i] = 0
    return nums

C++ Solution

void moveZeroes(vector<int>& nums) {
    int insertPos = 0;
    for (int num : nums) {
        if (num != 0) nums[insertPos++] = num;
    }
    for (int i = insertPos; i < nums.size(); i++) {
        nums[i] = 0;
    }
}

Java Solution

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

Complexity

Time: O(n) — two linear passes over the array. Space: O(1) — non-zero elements are shifted in place with one pointer.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.