Back to DSA sheet

Move Zeroes

EasyArrays

Given an array, move all zeros to the end while keeping the relative order of the non-zero elements unchanged. Do it in place.

Input format (stdin): the first line has n. The second line has n integers. Output the rearranged array separated by spaces.

Examples
Input: 5 0 1 0 3 12
Output: 1 3 12 0 0
Non-zeros keep their order; the two zeros move to the back.
Input: 1 0
Output: 0
Constraints
  • 1 <= n <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
Sheets
Grind 75NeetCode 250Striver A2Z
move-zeroes.cpp3 sample tests
Loading editor
Test results

Run the sample tests to check your solution against expected output.

Custom input (stdin)
Output

Run your code to see its output.