Move Zeroes in Array to End - Optimal Approach

Move Zeroes in Array to End - Optimal Approach

Visualization

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.

Move Zeroes to End using Loop - Optimal Approach 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))

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]