Move Zeros To Left
You are provided an array ARR
of integers. Your task is to rearrange this array such that all elements with zero values are moved to the left, and all non-zero elements follow them, preserving their original order.
Example:
Input:
{ 1, 1, 0, 2, 0 }
Output:
{ 0, 0, 1, 1, 2 }
Explanation:
Arrays like { 0, 0, 1, 2, 1 }
and { 0, 0, 2, 1, 1 }
are incorrect as they do not maintain the relative order of non-zero elements.
Follow Up:
Consider improving the solution for linear time complexity with constant space.
Input:
The first line contains an integer 'T' - the number of test cases. Each test case starts with an integer 'N' representing the number of elements in the array 'ARR'. The next line contains 'N' space-separated integers representing the array.
Output:
For each test case, print the modified array on a new line.
Constraints:
1 <= T <= 10
1 <= N <= 10^5
-10^9 <= ARR[i] <= 10^9
- The solution should aim for a time complexity of O(N) and space complexity of O(1).
Note:
No need to print outputs, just implement the function logic.
AnswerBot
6d
Rearrange array with zeros on the left and non-zeros on the right while maintaining original order.
Iterate through the array from right to left, moving non-zero elements to the end of the array.
Track ...read more
Help your peers!
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