Two Pointers Easy
Move Zeroes: Solution and Approach
Move all zeros in an array to the end while keeping the order of the non-zero numbers. Do it in place, without making a copy.
Similar questions reported in: TCS, Wipro, Capgemini, Cognizant
Example
- Input:
- nums = [0, 1, 0, 3, 12]
- Output:
- [1, 3, 12, 0, 0]
Brute force first
Build a new array of non-zero values and pad it with zeros. This uses O(n) extra space, which the problem doesn't allow.
The better idea
Use two pointers. A write pointer marks where the next non-zero number goes. Scan with a read pointer and swap each non-zero number into the write position.
Steps
- Set write = 0.
- For read from 0 to n - 1: if nums[read] is not 0, swap nums[read] and nums[write], then write += 1.
- When the loop ends, every number after write is 0.
Code
def move_zeroes(nums):
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[read], nums[write] = nums[write], nums[read]
write += 1public void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
int tmp = nums[read];
nums[read] = nums[write];
nums[write] = tmp;
write++;
}
}
}Complexity
Time: O(n)
Space: O(1)
Edge cases to test
- All zeros, or no zeros at all.
- A single element.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.