AlgoFrames

Move zeroes to the end in place

Challenge · Write code · about 15 min

Move every 0 in nums to the end while keeping the other values in their original order. Change the array in place and return it.

Shifting values left for each zero is O(n²). Find an O(n) way with O(1) extra space.

Example 1

Input:

[[0,1,0,3,12]]

Output:

[1,3,12,0,0]

Example 2

Input:

[[0]]

Output:

[0]

A single zero stays where it is.

Constraints

  • 0 ≤ nums.length ≤ 10,000
  • -10,000 ≤ nums[i] ≤ 10,000

Learn the idea first: Arrays: indexing, traversal, insertion and deletion costs, a visual lesson.

More Arrays: indexing, traversal, insertion and deletion costs problems