Sort 0s, 1s, and 2s Problem Statement
You are provided with an integer array/list ARR
of size 'N' which consists solely of 0s, 1s, and 2s. Your task is to write a solution to sort this array/list.
Input:
The first line contains an integer 'T' which denotes the number of test cases. For each test case, the first line contains an integer 'N' denoting the size of the array/list. The second line contains 'N' space-separated integers representing the elements of the array/list.
Output:
For each test case, output the sorted array/list ARR
as space-separated integers. Each test case should be printed on 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
Note:
Try to implement the solution with a 'Single Scan' approach, meaning you should attempt to sort the array by iterating over it just once. You are required to modify the given array/list directly.

AnswerBot
4mo
Sort an array of 0s, 1s, and 2s in linear time with a single scan approach.
Use three pointers to keep track of the positions of 0s, 1s, and 2s in the array.
Iterate through the array once and swap elem...read more

vastladooxen
3y
works at
vector<int> solve(int n, vector<int> arr){ int low = 0; int high = n-1; int mid = 0; while(mid <= high){ switch(arr[mid]){ case 0: swap(arr[mid++], arr[low++]); break; case 1: mid++; br...read more
Help your peers!
Add answer anonymously...
Maersk Software Developer interview questions & answers
A Software Developer was asked 12mo agoQ. What is a decorator in Python?
A Software Developer was asked Q. Architecture of current project
A Software Developer was asked Q. Shortest Path in an Unweighted Graph The city of Ninjaland is represented as an ...read more
Popular interview questions of Software Developer
A Software Developer was asked 12mo agoQ1. What is a decorator in Python?
A Software Developer was asked Q2. Architecture of current project
A Software Developer was asked Q3. Shortest Path in an Unweighted Graph The city of Ninjaland is represented as an ...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

