Move Zeros to End

Easy~10 min

Given an array of integers nums, move all zeros to the end of the array while preserving the relative order of the non-zero elements. Return the modified array.

For example, given [0, 1, 0, 3, 12], the result should be [1, 3, 12, 0, 0].

Examples

Example 1
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Explanation: Non-zero elements 1, 3, 12 keep their relative order and zeros move to the end.
Example 2
Input: nums = [0, 0, 0]
Output: [0, 0, 0]
Explanation: All elements are zeros, so the array stays the same.
Example 3
Input: nums = [1, 2, 3]
Output: [1, 2, 3]
Explanation: No zeros to move, so the array is unchanged.

Constraints

  • 0 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run