Move Zeros To Left
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?
Input Format :
The first line of the input contains an integer 'T' representing the number of test cases or queries to be processed.
Then the 'T' test case follows.
The first line of each test case contains an integer 'N' denoting the number of elements in the array 'ARR'.
The second line of each test contains 'N' space-separated integers denoting the array elements.
Output Format :
For each test case, print the modified array in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^5
-10^9 <= ARR[i] <= 10^9
Where 'T' denotes the number of test cases, 'N' denotes the number of elements in the array ‘ARR’ respectively, and 'ARR[i]' denotes the ’i-th’ element of the array 'ARR'.
Time limit: 1 second
CodingNinjas
author
2y
I have used two pointer approach to solve it
CodingNinjas
author
2y
Solution Using Extra space
The idea is to use an extra vector to store all the non-zero elements while maintaining their relative order. So we will first add all the non-zero elements to a vector and t...read more
CodingNinjas
author
2y
Two Pointers Based Approach
The idea is to use two pointers reader and writer to store the current reading index and the current writing index. We will initially place both the pointers at the end of t...read more
Add answer anonymously...
Top ACKO Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app