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:
The runtime complexity if this solution is linear, O(n).
The memory complexity of this solution is constant, O(1).
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_index points to 0, skip.
If read_index points to a non-zero value, write the value at read_index to write_index and decrement write_index.
Assign zeros to all the values before the write_index and to the current position of write_index as well.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!