Move All Zeros to the End of an Array
Problem Statement
Given an array of integers, move all the zero elements to the end of the array while maintaining the relative order of non-zero elements.
This operation should be done efficiently without disturbing the sequence of non-zero values.
Example
Example 1
Input:
arr = [0, 1, 0, 3, 12]
Output:
[1, 3, 12, 0, 0]
Explanation:
All non-zero elements retain their original order, and all zeros are shifted to the end.
Example 2
Input:
arr = [1, 2, 3, 4]
Output:
[1, 2, 3, 4]
Explanation:
There are no zeros, so the array remains unchanged.
Example 3
Input:
arr = [0, 0, 0, 5]
Output:
[5, 0, 0, 0]
Why This Problem Is Important
This is a classic array manipulation problem that appears frequently in:
- Coding interviews
- Online assessments
- Real-time data cleaning
- Memory-efficient algorithms
It helps in understanding:
- In-place array modification
- Two-pointer technique
- Stability of elements (order preservation)
Approaches to Solve the Problem
- Naive Approach (Using Extra Array)
- Optimized Approach (In-Place Using Two Pointers)
Approach 1: Naive Method (Using Extra Space)
Idea
- Create a new array.
- First copy all non-zero elements.
- Then append all zeros at the end.
Algorithm
- Create a new array result.
- Traverse the original array and copy non-zero elements into result.
- Count the number of zeros.
- Append zeros at the end of result.
- Print the result.
Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
C Implementation
#include<stdio.h>
int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = 5;
int result[5];
int index = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
result[index++] = arr[i];
}
}
while (index < n) {
result[index++] = 0;
}
printf("Array after moving zeros to end: ");
for (int i = 0; i < n; i++) {
printf("%d ", result[i]);
}
return 0;
}
Output
Array after moving zeros to end: 1 3 12 0 0
C++ Implementation
#include<iostream>
using namespace std;
int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = 5;
int result[5];
int index = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
result[index++] = arr[i];
}
}
while (index < n) {
result[index++] = 0;
}
cout << "Array after moving zeros to end: ";
for (int i = 0; i < n; i++) {
cout << result[i] << " ";
}
return 0;
}
Java Implementation
public class MoveZeros {
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
int n = arr.length;
int[] result = new int[n];
int index = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
result[index++] = arr[i];
}
}
while (index < n) {
result[index++] = 0;
}
System.out.print("Array after moving zeros to end: ");
for (int num : result) {
System.out.print(num + " ");
}
}
}
Python Implementation
arr = [0, 1, 0, 3, 12]
result = []
for num in arr:
if num != 0:
result.append(num)
while len(result) < len(arr):
result.append(0)
print("Array after moving zeros to end:", result)
C# Implementation
using System;
class Program {
static void Main() {
int[] arr = {0, 1, 0, 3, 12};
int[] result = new int[arr.Length];
int index = 0;
foreach (int num in arr) {
if (num != 0) {
result[index++] = num;
}
}
while (index < arr.Length) {
result[index++] = 0;
}
Console.Write("Array after moving zeros to end: ");
foreach (int num in result) {
Console.Write(num + " ");
}
}
}
JavaScript Implementation
let arr = [0, 1, 0, 3, 12];
let result = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== 0) {
result.push(arr[i]);
}
}
while (result.length < arr.length) {
result.push(0);
}
console.log("Array after moving zeros to end:", result);
Approach 2: Optimized Method (In-Place Using Two Pointers)
Idea
- Use a pointer index to track where the next non-zero element should be placed.
- Traverse the array.
- Every time a non-zero element is found, place it at arr[index] and increment index.
- After traversal, fill remaining positions with zeros.
Algorithm
- Initialize index = 0.
- Traverse the array:
- If element is non-zero, place it at arr[index].
- Increment index.
- Fill remaining elements from index to n-1 with zeros.
Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1) (in-place)
C Implementation (Optimized)
#include<stdio.h>
int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = 5;
int index = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[index++] = arr[i];
}
}
while (index < n) {
arr[index++] = 0;
}
printf("Array after moving zeros to end: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
When to Use Which Approach?
| Scenario | Best Choice |
|---|---|
| Learning basics | Naive method |
| Memory constraints | In-place method |
| Interview questions | Two-pointer approach |
| Real-world systems | Optimized approach |
Summary
Moving all zeros to the end of an array is a foundational array problem that strengthens understanding of traversal, in-place updates, and order preservation.
The naive approach is simple and intuitive but uses extra memory.
The optimized two-pointer approach achieves the same result with constant space and linear time, making it ideal for interviews and large datasets.
Mastering this problem prepares you for more advanced array manipulation techniques such as partitioning, stable rearrangements, and sliding window problems.
