Medium java streams

Move all zeroes to the end or the front

The 30 second answer

With streams I concatenate two filtered passes: the non-zero values and then the zeroes, or the other way round for zeroes first. It is stable but builds a new array. The version most interviewers actually want is in place: a write pointer copies every non-zero value forward, then fills the rest with zeroes. That is O(n) time and O(1) extra space.

Could you say this in an interview?

Stream version (new array, order of non-zero values kept):

int[] nums = {0, 1, 0, 3, 12};

int[] zeroesLast = IntStream.concat(
        Arrays.stream(nums).filter(n -> n != 0),
        Arrays.stream(nums).filter(n -> n == 0))
    .toArray();
// [1, 3, 12, 0, 0]

int[] zeroesFirst = IntStream.concat(
        Arrays.stream(nums).filter(n -> n == 0),
        Arrays.stream(nums).filter(n -> n != 0))
    .toArray();
// [0, 0, 1, 3, 12]

In-place two-pointer version:

static void moveZeroesToEnd(int[] nums) {
    int write = 0;
    for (int x : nums) {
        if (x != 0) nums[write++] = x;
    }
    while (write < nums.length) nums[write++] = 0;
}

static void moveZeroesToFront(int[] nums) {
    int write = nums.length - 1;
    for (int read = nums.length - 1; read >= 0; read--) {
        if (nums[read] != 0) nums[write--] = nums[read];
    }
    while (write >= 0) nums[write--] = 0;
}

For zeroes first, the scan runs from the right so the non-zero values keep their relative order.

Complexity: both versions are O(n) time. The stream version reads the array twice and allocates a new array of size n. The two-pointer version reads it once and uses O(1) extra space.

Edge cases: an empty array, an array with no zeroes, and an array of only zeroes all work unchanged in both versions. With a List of Integer, compare with n != 0 after unboxing, not with != on two Integer objects.

What interviewers listen for: this is usually asked as an in-place array problem. Show the stream version only if they ask for streams, then say it is not in place and offer the two-pointer loop. Collectors.partitioningBy(n -> n != 0) also works, but it still allocates two lists.

Sources (2)
  1. IntStream.concat and filterdocs.oracle.com
  2. Stream.concat (ordering of the result)docs.oracle.com