Remove all zeros from O (n) array, no extra memory

COULD you offer me the best algorithm for removing all zeros from a given array in O (n) time and without external memory. For example, 1 2 0 0 3 2 0 2 becomes 1 2 3 2 2

+4
source share
1 answer

use two pointers - one for reading and one for writing.

  • Iterate using a reader pointer to an array - if the element is zero, increase it only.
  • If the element is not equal to zero, write it and increase both pointers.
+16
source

Source: https://habr.com/ru/post/1414345/


All Articles