Given an array of integers, move all zero elements to the end while preserving the order of the other elements.
We are supposed to alter the given array, therefore let's make use of it.
We want to scan the array to find all non zero elements and put them to the front of the array, then fill the rest of the positions with zeros.
We notice though that the first non zero element would be placed at the beginning of the array, then the next non zero would be placed after that and so on.
If an element is non zero and there were no zeros before it, it stays in its place.
Therefore we can use a pointer to track where would we insert a non zero element, then scan all other elements of the array.
When we encounter a non zero element, we copy it to the location pointed by our pointer UNLESS it's exactly our position. If we did move, we replace the current position with a zero. In both cases, we increase the pointer.
We can process the array in O(N) time using constant space.
You can check my implementation of moveZeros on my Gist along with some tests in MoveZerosJTests.
No comments:
Post a Comment
With great power comes great responsibility