Menu
CoddyTech

Move Zeroes

You get an array of integers nums. Move every 0 to the end of the array and keep the other values in the order they had. Return the rearranged array, which has the same length as nums.

Function

moveZeroes(nums: integer-array) → integer-array
numsinteger-array
the array of integers to rearrange
Returnsinteger-array
nums with the non-zero values first, in their original order, and every 0 at the end

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -105 ≤ nums[i] ≤ 105

Examples

Input
nums = [0, 4, 0, 7, 2]
Output
[4, 7, 2, 0, 0]
Explanation
The values that are not 0 are 4, 7 and 2, and they keep that order at the front. The two 0s fill the last two places.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Can you move every 0 to the front instead, keeping the other values in their order, in one pass with O(1) extra memory?

Reset code
def moveZeroes(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [0, 4, 0, 7, 2]

Expected

[4, 7, 2, 0, 0]