Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

algorithm

COuld you suggest me the best algorithm to remove all zeros from 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

like image 481
renathy Avatar asked Dec 04 '22 16:12

renathy


1 Answers

use two pointers - one for read and one for write.

  • Iterate with the reader pointer on the array - if the element is zero increase only it.
  • If the element is not zero - write it and increase both pointers.
like image 198
amit Avatar answered Jan 15 '23 22:01

amit