v9.1.1
Menu

Move Zeroes

easyFREEArrays & StringsMeta DSA

Given an integer array nums, move all 0's to the end while maintaining the relative order of the non-zero elements.

You must do this in-place without making a copy of the array.

The function returns nothing. The tests print nums after the call as space-separated integers, so the array you were given must hold the result.

Example

Input
0,1,0,3,12
Output
1 3 12 0 0
Reasoning
  • Input: nums is the list 0,1,0,3,12, so n=5n = 5. It holds z=2z = 2 zeros (positions 0 and 2) and the non-zero values 1, 3, 12, in that order.
  • What stays fixed: the result is the same 5 values rearranged. Nothing is added or removed.
  • Front of the result: non-zero values keep their original relative order, so positions 0 to 2 become 1, 3, 12. This is not sorting: for the list 0, 5, 0, 2 the answer would start 5, 2.
  • Where each value lands: a non-zero value moves left by the number of zeros before it. 1 had one zero ahead (position 1 to 0); 3 and 12 each had two (positions 3 to 1 and 4 to 2).
  • Back of the result: the z=2z = 2 zeros fill positions n−z=3n - z = 3 through 4, giving 1 3 12 0 0.
  • Notice: a list with no zeros, such as 1, 2, 3, comes back unchanged, and a lone 0 stays put.

Constraints

  • 1 <= len(nums) <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Learn this in

More from Meta DSA

solution.py

Test results

Sign in to run your code against the test cases.