Problem Statement#
Given an integer array, move all elements that are 0 to the left while maintaining the order of other elements in the array. The array has to be modified in-place. Let’s look at the following integer array:
After moving all zeros to the left, the array should look like this:
Solution#
Solution Explanation#
Runtime complexity#
The runtime complexity if this solution is linear, O(n).
Memory complexity#
The memory complexity of this solution is constant, O(1).
Breakdown of solution#
Keep two markers: read_index and write_index and point them to the end of the array. Let’s take a look at an overview of the algorithm:
While moving read_index towards the start of the array:
If
read_indexpoints to0, skip.If
read_indexpoints to a non-zero value, write the value atread_indextowrite_indexand decrementwrite_index.Assign zeros to all the values before the
write_indexand to the current position ofwrite_indexas well.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!
Free Resources