Sort Array of 0s and 1s.

You are given an array ‘A’ of size ‘N’ containing only 0s and 1s. You have to sort the array by traversing the array only once.

For Example:
For the following array:
[0 1 1 1 0 0 1]

The output should be [0 0 0 1 1 1 1].
Note:
You have to sort the array in place.
Input Format:
The first line will contain a single integer ‘T’ denoting the number of test cases. Then the test cases follow.

The first line of each test case will contain a single integer ‘N’, denoting the size of the array.

The second line of each test case will contain ‘N’ space-separated integers, denoting the elements of the array.
Output Format:
For each test case, print the input array after sorting it.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 5
1 <= N <= 10^5
A[i] = 0 or 1

Time Limit: 1 sec.
CodingNinjas
author
2y

Technical knowledge

CodingNinjas
author
2y
Count 0s and 1s.

Count the number of 0s and 1s present in the input array. Suppose “count0” and “count1” be the number of 0s and 1s present respectively. Then replace the first “count0” elements in the...read more

CodingNinjas
author
2y
Two Pointer Approach

We will put all the 0s to the left side. Hence all the 1s will be automatically pushed to the right side. For that, we will take two variables - one will traverse the array from th...read more

Add answer anonymously...
Evoke Technologies Software Engineer 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
Get AmbitionBox app

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