Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Move Zeroes

LeetCode #283Easy
In-place · keep non-zeros in order

Given an integer array, move all zeros to the end in place while keeping the relative order of the non-zero elements.

Asked atMetaAmazonMicrosoft
step 1 / 35
0
1
0
3
12
[0][1][2][3][4]
aux (not yet allocated)
0
0
0
0
0
[0][1][2][3][4]
Brute force · extra array
1given arr (n elements)
2aux ← new array of size n filled with 0
3write ← 0
4for i ← 0 to n − 1:
5 if arr[i] ≠ 0:
6 aux[write++] = arr[i]
7copy aux back into arr
state
  • n5
  • goal[1, 3, 12, 0, 0]

line 1Move every zero to the end of arr while keeping the relative order of the non-zero elements.