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

 Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

    You must do this in-place without making a copy of the array.
    Minimize the total number of operations.

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
1529
Views Today
Views Today
1
Posted in Algorithm, Basics, Tip and tagged , , , .