Easy 0 solved 0% acceptance

Move Zeroes

Move every zero to the end while keeping the other order.

What you'll learn

  • Move elements with a write pointer
  • Keep the relative order of non-zero values
  • Fill the remaining positions with zeros

Problem

Return the list with all zeros moved to the end. The non-zero values keep their relative order.

Implement move_zeroes(numbers).

Input

numbers: The list of integers.

Output

Return the rearranged list.

Constraints

0 ≤ length ≤ 100,000

Examples

Example 1
Input:
numbers = [0, 1, 0, 3, 12]

Expected output:
expected = [1, 3, 12, 0, 0]
Input:
std::vector<long long> numbers = {0, 1, 0, 3, 12};

Expected output:
std::vector<long long> expected = {1, 3, 12, 0, 0};
Input:
long[] numbers = new long[] {0, 1, 0, 3, 12};

Expected output:
long[] expected = new long[] {1, 3, 12, 0, 0};

Explanation

1, 3, 12 keep their order and the two zeros go last: [1, 3, 12, 0, 0].

Example 2
Input:
numbers = [0, 0]

Expected output:
expected = [0, 0]
Input:
std::vector<long long> numbers = {0, 0};

Expected output:
std::vector<long long> expected = {0, 0};
Input:
long[] numbers = new long[] {0, 0};

Expected output:
long[] expected = new long[] {0, 0};

Explanation

Only zeros: the list stays [0, 0].

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Non-zero values should keep their order while zeros drift to the end.

Hint 2

A two-pointer or write-index approach lets you rebuild the list in one pass.

Hint 3

Do not reorder the non-zero values when compacting them.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.