PIXELBANKv8.2.1
Menu

Move Zeroes

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

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

Output the modified array as space-separated integers.

Example:

Input:
0,1,0,3,12
Output:
1 3 12 0 0
Reasoning:
  • We initialize two pointers, one at the beginning of the array to track non-zero elements and one to iterate through the array.
  • As we iterate through the array, we check each element: if it's non-zero, we swap it with the element at the non-zero pointer and move the non-zero pointer forward.
  • The non-zero pointer keeps track of the position where the next non-zero element should be placed, thus maintaining the relative order of non-zero elements.
  • After iterating through the entire array, all non-zero elements are moved to the front, and the remaining space is filled with the zero elements, resulting in the output: 1 3 12 0 0.

Constraints:

  • 1 <= len(nums) <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
Editor

Test Results

0/0
Run code to see test results.