Binary Array Sorting Problem Statement

You are provided with a binary array, i.e., an array containing only 0s and 1s. Your task is to sort this binary array and return it after sorting.

Input:

 The first line contains an integer ‘T’ denoting the number of test cases.
The following ‘2*T’ lines correspond to the test cases.
The first line of each test case contains an integer ‘N’ representing the size of the array.
The second line of each test case contains ‘N’ space-separated integers comprising 0s and 1s, which are the elements of the array.

Output:

For each test case, output ‘N’ space-separated integers that represent the elements of the sorted binary array on a separate line.
Each test case should be printed on a new line.

Example:

Input:
2
5
1 0 1 0 1
4
0 0 1 1
Output:
0 0 1 1 1
0 0 1 1

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 104
  • 0 <= arr[i] <= 1

Note

You do not need to print anything; the function should solely implement the logic for sorting.

Follow Up

1. Can you achieve the solution in linear time and constant space?
2. Is it possible to accomplish this in a single traversal?
AnswerBot
4mo

Yes, the binary array sorting problem can be solved in linear time and constant space by using a two-pointer approach.

  • Use two pointers, one starting from the beginning of the array and the other start...read more

Help your peers!
Select
Add answer anonymously...

Top Senior Android Developer Interview Questions Asked at Times Internet

Q. Data structure and algorithm : find maximum sum subarray. Separate zeroes and on...read more
Q. How does RecyclerView work internally?
Q. Maximum Subarray Sum Problem Statement Given an array arr of length N consisting...read more
Senior Android Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits