Back to ArraysMove Zeroes
Easy

Move Zeroes

EasyMust DoTwo Pointers

Given an array of integers, move every 0 to the end while keeping the relative order of the non-zero elements the same, all done in place.

Examples

Example 1

Input:
nums = [0,1,0,3,12]
Output:
[1,3,12,0,0]

Explanation: Every non-zero value keeps its original relative order; the three zeros are pushed to the end.

Example 2

Input:
nums = [0,0,0]
Output:
[0,0,0]

Explanation: No non-zero values exist, so the array is unchanged.

Example 3

Input:
nums = [1,2,3]
Output:
[1,2,3]

Explanation: No zeros exist, so nothing moves.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Follow-up

Can you minimize the total number of swaps performed on elements that are already in their correct final position?

Loading editor…

Code execution is coming soon.