Move Zeros to the End

easy Arrays

Problem

Read an array. Move all zeros to the end. Keep the order of the other elements. Print the new array.

Constraints

  • 1 <= n <= 10^5

Examples

Input

5
0 1 0 3 12

Output

1 3 12 0 0

Solutions

Best approachTime O(n)Space O(1)

The read pointer scans the array. The write pointer marks where the next non-zero value belongs. This works in place with O(1) extra memory.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The array with zeros at the end.
 * Approach: Two pointers: read and write.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        // Step 1: write is the place where the next non-zero value goes.
        int write = 0;

        // Step 2: Move every non-zero value to the front, in the same order.
        for (int read = 0; read < a.length; read++) {
            if (a[read] != 0) {
                a[write] = a[read];
                write++;
            }
        }

        // Step 3: Fill the rest of the array with zeros.
        while (write < a.length) {
            a[write] = 0;
            write++;
        }
        return a;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. Which pointer moves on every step?