This problem was posed by Irfan Baqui.

Write an algorithm that shifts all zeros in an array in place to the right most indexes.

For example, [0, 1, 1, 1, 0] should become [1, 1, 1, 0, 0]

Problem posed by Irfan Baqui.

My solution runs in linear time. I took a different approach to solving the problem.

I use two loops to traverse the array. One that traverses from the front and another from the back. When the two meet, the algorithm completes. When the index at the front encounters a 0, it swaps with the next non-zero index at the back. And when the index at the back encounters a 0, the index is decremented.

Leave a Reply