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.

vastladooxen
2y
student at
JK institute of engineering
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
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

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