Introduction
The Move Zeroes problem involves shifting all zero elements to the end of the array while maintaining the relative order of non-zero elements.
Given an array arr[] of size n, the task is to move all 0 s to the end without changing the order of the remaining elements.
This is a popular beginner-level array problem that helps in understanding array manipulation, Two Pointer Technique, and in-place operations.
Input: arr[] = [0, 1, 0, 3, 12]Output: [1, 3, 12, 0, 0]
Explanation:
All non-zero elements are shifted to the front.
All zeroes are moved to the end.
Input: arr[] = [4, 0, 5, 0, 0, 2]
Output: [4, 5, 2, 0, 0, 0]
Explanation:
Relative order of non-zero elements remains unchanged.
All zeroes are placed at the end.
Constraints
1 <= n <= 10^5
-10^9 <= arr[i] <= 10^9
Approach 1 : Brute Force (Using Extra Array)
Explanation
The simplest way to solve this problem is:
- Store all non-zero elements in another array
- Count the number of zeroes
- Append zeroes at the end
This approach is easy to understand but uses extra space.
Steps
- Create an empty array.
- Traverse the original array.
- Store all non-zero elements.
- Count total zeroes.
- Append all zeroes at the end.
- Return the final array.
Dry Run
Input Array: [0, 1, 0, 3, 12]Traverse 0:
Zero found
Count zeroes
Traverse 1:
Non-zero element
Store 1
Traverse 0:
Zero found
Count zeroes
Traverse 3:
Store 3
Traverse 12:
Store 12
Append two zeroes at the end
Final Result:
[1, 3, 12, 0, 0]
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
The array is traversed once.
Space Complexity: O(n)
Explanation:
An extra array is used to store non-zero elements.
- Maintain one pointer for placing non-zero elements
- Traverse the array
- Whenever a non-zero element is found:
- swap it with the current position
- Initialize pointer j=0.
- Traverse the array using index i.
- If current element is non-zero:
- swap arr[i] and arr[j]
- increment j.
- Continue traversal.
- Final array will contain all zeroes at the end.
Approach 2 : Optimized Solution (Two Pointer Technique)
Explanation
Instead of using another array, we can solve this problem in-place using the Two Pointer Technique.
The idea is:
This keeps all non-zero elements at the front and pushes zeroes to the end automatically.
Steps
Dry Run
Input Array: [0, 1, 0, 3, 12]Initially:
j = 0
Traverse 0:
Element is zero
No swap required
Traverse 1:
Non-zero element found
Swap arr[1] and arr[0]
Array becomes:
[1, 0, 0, 3, 12]
Increment j = 1
Traverse 0:
Element is zero
No swap required
Traverse 3:
Swap arr[3] and arr[1]
Array becomes:
[1, 3, 0, 0, 12]
Increment j = 2
Traverse 12:
Swap arr[4] and arr[2]
Array becomes:
[1, 3, 12, 0, 0]
Final Result:
[1, 3, 12, 0, 0]
Optimized Code