Sort 0 1 2 Problem Statement
Given an integer array arr
of size 'N' containing only 0s, 1s, and 2s, write an algorithm to sort the array.
Input:
The first line contains an integer 'T' representing the number of test cases. Each test case consists of two lines. The first line contains an integer 'N', the size of the array. The second line contains 'N' space-separated integers, the elements of the array.
Output:
For each test case, output the sorted array as space-separated integers in a new line.
Example:
Input:
2
5
0 2 1 2 0
3
2 1 0
Output:
0 0 1 2 2
0 1 2
Constraints:
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 5 * 105
- 0 ≤ arr[i] ≤ 2
- Time Limit: 1 sec
Note:
Try to solve the problem using a single scan over the array. You need to modify the array in-place and do not return anything.

AnswerBot
4mo
Sort an array of 0s, 1s, and 2s in linear time complexity.
Use three pointers to keep track of 0s, 1s, and 2s while iterating through the array.
Swap elements based on the values encountered to sort the...read more
Help your peers!
Add answer anonymously...
UBS C Developer interview questions & answers
A C Developer was asked Q. Preorder Traversal of a BST Problem Statement Given an array PREORDER representi...read more
A C Developer was asked Q. Find Maximum Number by At-most K Swaps Given an array of non-negative integers r...read more
A C Developer was asked Q. BST Node Deletion Problem Given a binary search tree (BST) and a key value K, yo...read more
Popular interview questions of C Developer
A C Developer was asked Q1. Preorder Traversal of a BST Problem Statement Given an array PREORDER representi...read more
A C Developer was asked Q2. Find Maximum Number by At-most K Swaps Given an array of non-negative integers r...read more
A C Developer was asked Q3. BST Node Deletion Problem Given a binary search tree (BST) and a key value K, yo...read more
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

