ExamAdda Logo

Move Zeroes

Easy

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

You must modify the array in-place.

Example 1

Input

n = 5
nums = [0, 1, 0, 3, 12]

Output

[1, 3, 12, 0, 0]

Explanation

All non-zero elements remain in their original relative order, while the zeroes are moved to the end.

Example 2

Input

n = 5
nums = [0, 0, 1, 2, 3]

Output

[1, 2, 3, 0, 0]

Explanation

The three non-zero elements are kept in the same order and both zeroes are moved to the end.

Constraints

1 <= n <= 10^5
-10^9 <= nums[i] <= 10^9
The array must be modified in-place.
The relative order of non-zero elements must be maintained.

Hints:

Hint 1

Use a pointer to track the position where the next non-zero element should be placed.

Hint 2

Traverse the array and move every non-zero element toward the front.

Auto
Loading editor...
Input

Expected Output