Move Zeroes

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

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

You must do this in-place without making a copy of the array.

Examples

Example 1:

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

Output: [1,3,12,0,0]

Explanation: All zeroes are moved to the end while 1, 3, and 12 maintain their original relative order.

Example 2:

Input: nums = [0]

Output: [0]

Explanation: The array has only one element, which is already a zero at the end.

Example 3:

Input: nums = [1,2,3]

Output: [1,2,3]

Explanation: There are no zeroes, so the array remains unchanged.

Constraints

  • 1 <= nums.length <= 10⁴
  • -2³¹ <= nums[i] <= 2³¹ - 1
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle