easyArray Basics (1D)

Move Zeros to End

Move every zero to the end in place while preserving the order of the nonzero values. Do not allocate a second array.

Work through the cases

3 examples

Input notation

One nonempty line of space-separated integers.

Expected result

The resulting array.
Case 1

Input

0 4 0 2 7

Expected output

4 2 7 0 0
Case 2

Input

0 0

Expected output

0 0
Case 3

Input

1 2 3

Expected output

1 2 3

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Zeros must go to the end while nonzeros keep their order. Let k be the next slot for a nonzero. Each nonzero is swapped with nums[k] and k advances, so the prefix of length k is the original nonzero sequence.

We use a pointer k to record the current position to insert, initially k = 0.

Then we iterate through the array nums, and each time we encounter a non-zero number, we swap it with nums[k] and increment k by 1.

This way, we can ensure that the first k elements of nums are non-zero, and their relative order is the same as in the original array.

The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).

class Solution {
    public void moveZeroes(int[] nums) {
        int k = 0, n = nums.length;
        for (int i = 0; i < n; ++i) {
            if (nums[i] != 0) {
                int t = nums[i];
                nums[i] = nums[k];
                nums[k++] = t;
            }
        }
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.

Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.