VOOZH about

URL: https://www.geeksforgeeks.org/dsa/move-zeroes-end-array/

⇱ Move all Zeros to End of Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Move all Zeros to End of Array

Last Updated : 26 Feb, 2026

Given an array of integers arr[], move all the zeros to the end of the array while maintaining the relative order of all non-zero elements.

Examples:

Input: arr[] = [1, 2, 0, 4, 3, 0, 5, 0]
Output: [1, 2, 4, 3, 5, 0, 0, 0]
Explanation: There are three 0s that are moved to the end.

Input: arr[] = [10, 20, 30]
Output: [10, 20, 30]
Explanation: No change in array as there are no 0s.

Input: arr[] = [0, 0]
Output: [0, 0]
Explanation: No change in array as there are all 0s.

[Naive Approach] Using Temporary Array - O(n) Time and O(n) Space

The idea is to use a temporary array of the same size, copy all non-zero elements into it, fill the remaining positions with zeros, and then copy the temporary array back to the original array.

Working:


Output
1 2 4 3 5 0 0 0 

[Better Approach] Two Traversals-O(n) Time and O(1) space

The idea is to move all the zeros to the end of the array while maintaining the relative order of non-zero elements using two traversals. Traverse the array once to move all non-zero elements to the front while maintaining order, then traverse the remaining positions and fill them with zeros.

Working:


Output
1 2 4 3 5 0 0 0 

[Expected Approach] One Traversal-O(n) Time and O(1) space

The idea is similar to the previous approach where we took a pointer, say count to track where the next non-zero element should be placed. However, on encountering a non-zero element, instead of directly placing the non-zero element at arr[count], we will swap the non-zero element with arr[count]. This will ensure that if there is any zero present at arr[count], it is pushed towards the end of array and is not overwritten.

Working:


Output
1 2 4 3 5 0 0 0 
Comment