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.
Details
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].
Problem:Move ZeroesEasy
Two Pointers
step 1 / 7
slow = 0, fast = 0: slow marks the next slot for a non-zero; fast will scan every element.
- slow=0· arr[0] = 0
- fast=0· arr[0] = 0
1FUNCTION moveZeroes(nums):2 slow = 03 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
Every step in words
Show all 7 steps
- slow = 0, fast = 0: slow marks the next slot for a non-zero; fast will scan every element.
- fast=0: nums[0]=0 is zero, skip. fast=1: nums[1]=1 is non-zero — swap nums[slow=0] and nums[fast=1]: [1,0,0,3,12]. slow advances to 1.
- fast=2: nums[2]=0 is zero. Do nothing; just advance fast. slow stays at 1. Array unchanged: [1,0,0,3,12].
- fast=3: nums[3]=3 is non-zero — swap nums[slow=1] and nums[fast=3]: [1,3,0,0,12]. slow advances to 2.
- fast=4: nums[4]=12 is non-zero — swap nums[slow=2] and nums[fast=4]: [1,3,12,0,0]. slow advances to 3.
- fast reaches n=5, the loop ends. All non-zero elements [1,3,12] are at the front in their original order; the two zeroes settled at the back.
- Final: [1, 3, 12, 0, 0].
Now solve it yourself
Watching is the first half. The second is writing it without the animation.