Move zeroes to the end
Move all zero values to the end of an integer array in place while preserving the order of non-zero values.
Course progress
Problem 63 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [0, 1, 0, 3, 12]
Expected output
1 3 12 0 0
What is happening?
Write the non-zero values 1, 3, and 12 in their original order, then fill the two remaining positions with zeroes.
Solution strategy
Build the right mental model
Write each non-zero value at the next open position, then fill the remaining suffix with zeroes.
Core concepts
arrays · two pointers
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for move-zeroes-to-end
using System;
class Program
{
static void MoveZeroes(int[] numbers)
{
int write = 0;
foreach (int number in numbers)
if (number != 0) numbers[write++] = number;
while (write < numbers.Length) numbers[write++] = 0;
}
static void Main()
{
int[] values = { 0, 1, 0, 3, 12 };
MoveZeroes(values);
Console.WriteLine(string.Join(" ", values));
}
}Knowledge check
Questions students often ask
What is the main idea behind move zeroes to the end?
Write each non-zero value at the next open position, then fill the remaining suffix with zeroes.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.