Interview 150

Move Zeroes

Problem
LC 283
File
interview150_LC283MoveZeroes.java
Path
pkg5leetcode/interview150/interview150_LC283MoveZeroes.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC283MoveZeroes.java
Approach
Write non-zero values forward; zero-fill rest.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC283MoveZeroes.java
1package pkg5leetcode.interview150;2 3/*4 * Move Zeroes | LC 2835 * APPROACH: Write non-zero values forward; zero-fill rest.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC283MoveZeroes {9    static void moveZeroes(int[] nums) {10        int k = 0;11        for (int x : nums) if (x != 0) nums[k++] = x;12        while (k < nums.length) nums[k++] = 0;13    }14 15    public static void main(String[] args) {16        int[] a = {0, 1, 0, 3, 12};17        moveZeroes(a);18        check(java.util.Arrays.equals(a, new int[]{1, 3, 12, 0, 0}), "case1");19        int[] b = {0};20        moveZeroes(b);21        check(java.util.Arrays.equals(b, new int[]{0}), "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}