Move Zeroes in Array to End using Loop - Optimal Algorithm

Problem Statement

Given an array of integers, your task is to move all the zeroes to the end of the array, while maintaining the relative order of non-zero elements.

This must be done in-place without making a copy of the array, and ideally in a single pass using an optimal approach.

If the array is empty, return it as is.

Examples

Input Array Output Array Description
[0, 1, 0, 3, 12] [1, 3, 12, 0, 0] All non-zero elements kept in order, zeroes pushed to the endVisualization
[1, 2, 3] [1, 2, 3] No zeroes present, array remains unchangedVisualization
[0, 0, 0] [0, 0, 0] All elements are zeroes, no changes neededVisualization
[4, 0, 5, 0, 6] [4, 5, 6, 0, 0] Zeroes moved to end, non-zero order maintainedVisualization
[] [] Empty array, returns emptyVisualization
[0] [0] Single element which is zeroVisualization
[9] [9] Single non-zero element, unchangedVisualization
[0, 1, 0, 2, 0, 3] [1, 2, 3, 0, 0, 0] Multiple interleaved zeroes correctly pushed to the endVisualization

Visualization Player

Solution

To solve the problem of moving all zeroes in the array to the end, we need to consider several different situations. The goal is to rearrange the array so that:

  • All non-zero elements stay in the same relative order.
  • All zeroes are placed at the end.
  • The array is modified in-place, meaning we do not use extra space like a new array.

Case 1: No zeroes in the array

If there are no zeroes in the array, like in [1, 2, 3], then the array is already in the correct format. Nothing needs to be changed, and the output is the same as the input.

Case 2: All zeroes

If the array only contains zeroes, like [0, 0, 0], then there are no non-zero elements to shift. The array remains as it is.

Case 3: Zeroes scattered among non-zero elements

This is the most common case. For example, in the array [0, 1, 0, 3, 12], we want to move all the non-zero elements forward while tracking their original order: [1, 3, 12]. Once these are placed at the front, we fill the remaining slots in the array with zeroes to get the final result [1, 3, 12, 0, 0].

Case 4: Single-element array

If the array has only one element, it can either be 0 or a non-zero number. In both cases, there’s no movement needed. The array remains unchanged.

Case 5: Empty array

If the array is empty, then we simply return it as is. There’s no work to be done since there are no elements at all.

How does the optimal approach work?

The efficient way to do this is by using a pointer (let’s say nonZeroIndex) to track the position where the next non-zero element should go. As we loop through the array:

  • Every time we see a non-zero element, we place it at the nonZeroIndex and move that pointer forward.
  • Once all non-zero elements have been moved, the rest of the array (from nonZeroIndex to end) is filled with zeroes.

This approach ensures that we use only one loop to process all elements and perform the operation in-place with O(n) time and O(1) space complexity.

Algorithm Steps

  1. Given an array of numbers arr.
  2. Initialize a pointer nonZeroIndex to 0.
  3. Iterate through each element of the array.
  4. If the element is non-zero, assign it to arr[nonZeroIndex] and increment nonZeroIndex.
  5. After the loop, fill the rest of the array from nonZeroIndex to the end with zeroes.

Code

Python
JavaScript
Java
C++
C
def move_zeroes(arr):
    nonZeroIndex = 0
    for i in range(len(arr)):
        if arr[i] != 0:
            arr[nonZeroIndex] = arr[i]
            nonZeroIndex += 1
    for i in range(nonZeroIndex, len(arr)):
        arr[i] = 0
    return arr

# Sample Input
arr = [0, 1, 0, 3, 12]
print("Result:", move_zeroes(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even if no zeros are present, the algorithm still iterates through the entire array once to check each element.
Average CaseO(n)The algorithm goes through the array once to move non-zero elements and then fills the remaining positions with zeroes.
Worst CaseO(n)When all elements are zero or all are non-zero, the algorithm still performs a full scan and update in two linear passes.

Space Complexity

O(1)

Explanation: The algorithm performs all operations in-place using a constant number of variables, without using any extra space.

Detailed Step by Step Example

Let's move all zeroes to the end while maintaining the order of non-zero elements.

{ "array": [0,1,0,3,12], "showIndices": true }

Initialize nonZeroIndex = 0. We'll use this to track where the next non-zero element should go.

Check index 0

Element is 0. It's zero. Do nothing and move to next.

{ "array": [0,1,0,3,12], "showIndices": true, "highlightIndices": [0], "labels": { "0": "i", "-1": "nonZeroIndex" } }

Check index 1

Element is 1. It's non-zero, so move it to index 0.

{ "array": [1,1,0,3,12], "showIndices": true, "highlightIndices": [1], "labels": { "1": "i", "0": "nonZeroIndex" } }

Check index 2

Element is 0. It's zero. Do nothing and move to next.

{ "array": [1,1,0,3,12], "showIndices": true, "highlightIndices": [2], "labels": { "2": "i", "0": "nonZeroIndex" } }

Check index 3

Element is 3. It's non-zero, so move it to index 1.

{ "array": [1,3,0,3,12], "showIndices": true, "highlightIndices": [3], "labels": { "3": "i", "1": "nonZeroIndex" } }

Check index 4

Element is 12. It's non-zero, so move it to index 2.

{ "array": [1,3,12,3,12], "showIndices": true, "highlightIndices": [4], "labels": { "4": "i", "2": "nonZeroIndex" } }

Fill remaining positions with zeroes starting from index 3.

{ "array": [1,3,12,0,0], "showIndices": true, "labels": { "3": "start filling 0s" } }

Final Result:

[1,3,12,0,0]