Visualize

Pattern visualizer

Move Zeroes

Use a slow pointer to mark the next open slot for a non-zero value, and a fast pointer to scan ahead. Whenever fast finds a non-zero, swapping it into slow's slot never disturbs anything already placed — the elements before slow are already confirmed non-zero and in order — so one pass is enough to push every non-zero to the front while zeroes naturally settle at the back. Animated on: Given nums = [0, 1, 0, 3, 12], move all zeroes to the end while maintaining the relative order of the non-zero elements. Answer: [1, 3, 12, 0, 0]..

Two Pointers

time O(n)space O(1)step 1 / 7
0
[0]
1
[1]
0
[2]
3
[3]
12
[4]
line 2

slow = 0, fast = 0: slow marks the next slot for a non-zero; fast will scan every element.

Pseudocode
1FUNCTION moveZeroes(nums):
2 slow = 0
3 FOR fast from 0 to n-1:
4 IF nums[fast] != 0:
5 swap nums[slow] and nums[fast]
6 slow = slow + 1

← / → step · space play · Home restart

Where to practice Two Pointers