DDSA Solutions

Move All Zeroes to End

Time: O(n)
Space: O(1)
Advertisement

Intuition

Move all zeros to end while maintaining relative order of non-zeros. Two-pointer in-place.

Algorithm

  1. 1pos=0. For each num: if non-zero: arr[pos++]=num. Fill arr[pos..n-1] with 0.

Common Pitfalls

  • Same as LC 283. Single pass for non-zeros, then fill zeros. No extra space needed.
Move All Zeroes to End.java
Java
// Approach: Two-pointer: keep track of the insertion position for non-zero elements, fill rest with zeros.
// Time: O(n) Space: O(1)
class Solution {
    void pushZerosToEnd(int[] arr) {
        int d = 0, count = 0;
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            if (arr[i] != 0) {
                arr[d] = arr[i];
                d++;
            } else
                count++;
        }

        for (int i = n - 1; i >= (n - count); i--)
            arr[i] = 0;
    }
}
Advertisement
Was this solution helpful?