Move Zeroes – Algorithms

Come across a task in an Interview or a website that challenges you to this. The thing that intrigues me is a good challenge (and many a times I do struggle with it, I am no Genius) However it is still worth a try.

The challenge I came across was to move the zeroes to the end of an array. Think of it as moving a particular character/number but in this case it is zeroes.

Here’s the original problem

The first go

There are a couple of things here, the first criterion is not to create a copy of the array. It would have been so simpler if you could simple do the following

The methodology behind this is quite simple, we first get the number of items in the passed array, then we filter the array in place to remove any 0’s. This new array is shorter by the number of zeroes. So we simply add as many 0’s as required to make the array the same length as the array passed.

Views All Time
Views All Time
618
Views Today
Views Today
1
Posted in Algorithm, Basics, Tip and tagged , , , .