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 += 1

Complexity

Time: O(n). Space: O(1) in place.

Open Move Zeroes in Code Arena →