SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Move Zeroes

Description: Given array nums, move all zeroes to the end while keeping the relative order of the other elements. Return the modified array.

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Explanation: Non-zero elements keep their order

Example 2:

Input: nums = [1,2,3]
Output: [1,2,3]
Explanation: No zeroes, array unchanged

Constraints:

1 <= nums.length <= 10⁴

-2³¹ <= nums[i] <= 2³¹ - 1

Recommended time and space complexity

Aim for O(n) time and O(1) space — without creating a new array.


Hint 1

Creating a new array is easy, but the task asks for in-place.


Hint 2

Keep a pointer to where the next non-zero element should go.


Hint 3

Move all non-zero elements to the front, then fill the tail with zeroes.

A two pointers problem. Teaches transforming an array in place without extra memory while preserving relative order.

Expected Input :

[0,1,0,3,12]

Expected Output

[1,3,12,0,0]