Back

Move Zeroes

easy

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Test Cases

Copy an input into the main harness and Run to verify
Input
nums = [0,1,0,3,12]
Expected Output
[1,3,12,0,0]

Explanation: The non-zero values keep their original order; both zeroes slide to the back.

Input
nums = [0]
Expected Output
[0]

Constraints

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

Hints

Hint 1 — click to reveal

Think of one pointer marking where the next non-zero value belongs.

Hint 2 — click to reveal

Copy every non-zero forward first, then fill whatever is left with zeroes.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.