didxga didxga - 1 year ago 75
Java Question

Move all zero values in a big array to its front portion in a Time Efficiency way

You're given a big array with Integral type value, How do you move all zero values within it to the front portion of the array in a Time Efficiency way?

e.g. 0,1,72,3,0,5,9,0,6,51,0,3 ---> 0,0,0,0,1,72,3,5,9,6,51,3


Answer Source

If you want to keep the order between the other items, loop backwards copying all non-zero items, then fill up with zero items at the beginning:

int source = arr.Length - 1;
int dest = arr.Length - 1;
while (source >= 0) {
  if (arr[source] != 0) {
    arr[dest--] = arr[source];
while (dest >= 0) arr[dest--] = 0;

If the order of the items is not important, you can simply swap zero items with items at the beginning of the array:

int dest = 0;
for (int source = 0; source < arr.Length; source++) {
  if (arr[source] == 0) {
    arr[source] = arr[dest];
    add[dest++] = 0;

Both algorithms are O(n).

(Examples in C#, but it should be close enough as it's mostly a question about algorithms...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download