Sort 0 and 1 Problem Statement

Given an integer array ARR of size N containing only integers 0 and 1, implement a function to sort this array. The solution should scan the array only once without using any additional arrays.

Input:

The first line contains an integer 't', denoting the number of test cases or queries to be run. 
The next t lines contain:
- An integer 'N' representing the size of the array/list in each test case.
- 'N' single space-separated integers (all 0s and 1s) representing the elements in the array.

Output:

For each test case, print the sorted array elements in one row, separated by a single space. 
Output for every test case will be printed on a separate line.

Example:

Input:
2
5
0 1 1 0 1
3
1 0 0
Output:
0 0 1 1 1
0 0 1

Constraints:

  • 1 <= t <= 10^2
  • 0 <= N <= 10^5
  • Time Limit: 1 sec
Note:
You need to modify the given array/list itself. No need to return or print anything within the function.
AnswerBot
4mo

Sort an array of 0s and 1s in linear time without using additional arrays.

  • Use two pointers approach to swap 0s to the left and 1s to the right.

  • Maintain two pointers, one for 0s and one for 1s, and ite...read more

Help your peers!
Select
Add answer anonymously...

Nagarro Software Developer Intern interview questions & answers

A Software Developer Intern was asked Q. Word Break Problem Statement You are given a list of N strings called A. Your ta...read more
A Software Developer Intern was asked Q. Sort 0 and 1 Problem Statement Given an integer array ARR of size N containing o...read more
A Software Developer Intern was asked Q. Check If Binary Representation of a Number is Palindrome Given an integer N, det...read more

Popular interview questions of Software Developer Intern

A Software Developer Intern was asked Q1. Word Break Problem Statement You are given a list of N strings called A. Your ta...read more
A Software Developer Intern was asked Q2. Sort 0 and 1 Problem Statement Given an integer array ARR of size N containing o...read more
A Software Developer Intern was asked Q3. Check If Binary Representation of a Number is Palindrome Given an integer N, det...read more
Nagarro Software Developer Intern 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