Move Zeroes Visualizer & Step-by-Step Algorithm Solution

Move all zeros in an array to the end in-place while maintaining the relative order of the non-zero elements using two pointers.

Category: arrays | Difficulty: Easy

Tags: Two Pointers, Array, In-Place

Move Zeroes

Numbers Array (In-Place Modifications)
0
0
1
1
0
2
3
3
12
4
100%
state
left
right
nums[left]
nums[right]
length5
Initialization
1/37
Explanation

Start moveZeroes on [0, 1, 0, 3, 12]. Relocate all non-zero values forward in-place.

Source Code
1function moveZeroes(nums: number[]): void {
2 let left = 0;
3 for (let right = 0; right < nums.length; right++) {
4 if (nums[right]) {
5 nums[left] = nums[right];
6 left++;
7 }
8 }
9 while (left < nums.length) {
10 nums[left] = 0;
11 left++;
12 }
13}