Move Zeros to Left Problem Statement

Your task is to rearrange a given array ARR such that all zero elements appear at the beginning, followed by non-zero elements, while maintaining the relative order of non-zero elements.

Example:

Input:
ARR = [1, 1, 0, 2, 0]
Output:
[0, 0, 1, 1, 2]
Explanation:

The zero elements should be at the start, hence the rearranged array should be [0, 0, 1, 1, 2]. Arrays such as [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:
Attempt to solve this in linear time and constant space.

Input:

The first line contains an integer 'T' for the number of test cases.
Each test case consists of an integer 'N', the number of elements in the array 'ARR', followed by 'N' space-separated integers.

Output:

For each test case, output the modified array on a new line.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 105
  • -109 <= ARR[i] <= 109
  • Time limit: 1 second
Note:
Implement the function without printing output directly. The output will be managed by the system.
Anonymous
10mo
l=0 for r in range(len(arr1)): if arr1[r]==0 and r!=0: l=r-1 while l!=0 or arr1[r-1]!=0 and r!=0: arr1[l], arr1[r]=arr1[r], arr1[l] print(arr1) l-=1 r-=1
Help your peers!
Add answer anonymously...
Dell Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter