Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Move Zeros To Left
EASY
10 mins
26 upvotes
Arrays
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Arrays
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Move Zeros To Left

Contributed by
Prateek_18cb
Easy
yellow-spark
0/40
Avg time to solve 10 mins
Success Rate 90 %
Share
26 upvotes

Problem Statement

You are given an array 'ARR' of integers. Your task is to modify the array so that all the array elements having zero values get pushed to the left and all the array elements having non-zero value come after them while maintaining their relative order.

For example :
Consider the array { 1, 1, 0, 2, 0 }. 
For the given array the modified array should be {0,0,1,1,2} . 
Arrays { 0, 0, 1, 2, 1 } and  { 0, 0, 2, 1, 1 } are not the correctly reorganized array even if they have all the zero values pushed to the left as in both the arrays the relative order of non-zero elements is not maintained.
Follow Up :
Can you solve the problem in linear time, and constant space?
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
2 
5
1 2 0 0 1
3
1 0 0
Sample Output 1 :
0 0 1 2 1
0 0 1
Explanation for sample input 1 :
For the first test case, the given array is { 1, 2, 0, 0, 1 }, if we move all the zeros to the left the modified array becomes { 0, 0, 1, 2, 1} which is our final answer. 

For the second test case, the given array is { 1, 0, 0}, if we move all the zeros to the left the modified array becomes { 0, 0, 1} which is our final answer.
Sample Input 2 :
1
5
1 2 3 4 5
Sample Output 2 :
1 2 3 4 5
Reset Code
Full screen
Auto
copy-code
Console