Move Zeros to End

EasyArrayTwo PointersSorting

Description

Given an array of integers nums, return a new array with all non-zero values kept in their original order followed by all the zeros.

Examples

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

Keeping the non-zero values in order and pushing zeros to the back gives [1,3,12,0,0].

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

Keeping the non-zero values in order and pushing zeros to the back gives [1,2,3].

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

Keeping the non-zero values in order and pushing zeros to the back gives [5,0,0].

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • -10⁹ ≤ nums[i] ≤ 10⁹

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.