Move Zeroes
Easy · rating 950 · Arrays, Two Pointers
The first line contains n. The second line contains n integers. Print the array with all zeroes moved to the end, preserving the relative order of the non-zero elements.
Editorial
Approach
Keep a write pointer for the next non-zero slot. Scan the array; each time you hit a non-zero, place it at the write pointer and advance it. After the scan, fill the remaining slots with zeros. The relative order of non-zeros is preserved.
w = 0
for x in nums:
if x != 0:
nums[w] = x; w += 1
while w < len(nums):
nums[w] = 0; w += 1Complexity
Time: O(n). Space: O(1) in place.
Related problems
- Count Distinct (Sorted) — Medium
- Two Sum (Sorted) — Medium
- Interleave Arrays — Easy
- Low Stock Alert — Easy
- Max Consecutive Ones — Easy
- Plus One — Easy