Given an array, move all zeros to the end while keeping the order of other numbers.

Move all zeros to the end of an array in place, keeping the order of the other elements, in one pass with O(1) extra space.

0 0
Read Time:1 Minute, 38 Second

Example: [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0]. The non-zero numbers must stay in their original order, and you should do it in place.

Write pointer (O(n), O(1) space)

Keep a pointer w to the next position for a non-zero value. Copy each non-zero value there, then fill the rest with zeros.

static void moveZeros(int[] a) {
    int w = 0;
    for (int x : a) {
        if (x != 0) a[w++] = x;
    }
    while (w < a.length) a[w++] = 0;
}

Swap version (one pass, fewer writes when there are few zeros)

static void moveZerosSwap(int[] a) {
    int w = 0;
    for (int i = 0; i < a.length; i++) {
        if (a[i] != 0) {
            if (i != w) { int t = a[i]; a[i] = a[w]; a[w] = t; }
            w++;
        }
    }
}

Dry run on [0, 1, 0, 3, 12]

i=0 a[i]=0   skip                   w=0
i=1 a[i]=1   swap a[1],a[0] -> [1,0,0,3,12]   w=1
i=2 a[i]=0   skip                   w=1
i=3 a[i]=3   swap a[3],a[1] -> [1,3,0,0,12]   w=2
i=4 a[i]=12  swap a[4],a[2] -> [1,3,12,0,0]   w=3

Why not sort?

Sorting would put negatives first and change the order of the other numbers, and costs O(n log n). Using a second array works but uses O(n) extra space, which is usually what the interviewer asks you to avoid.

Edge cases

  • All zeros or no zeros.
  • Empty array or a single element.
  • Negative numbers stay in their original order.

Follow-ups

  • Move zeros to the front instead.
  • Remove duplicates from a sorted array in place (same write-pointer idea).
  • Segregate 0s, 1s and 2s (Dutch national flag).

This answer was written by Debugger’s Space as practice material. See how Infosys hires, step by step, and more Infosys practice questions.

Previous post Why IBM?
Next post Dry run this loop and tell me the output (pseudocode with nested loops).
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Close
0
Would love your thoughts, please comment.x
()
x