Sort 0 1 2

Easy
0/40
Average time to solve is 22m
1266 upvotes
Asked in companies
WalmartZS AssociatesIntuit

Problem statement

You have been given an integer array/list(ARR) of size 'N'. It only contains 0s, 1s and 2s. Write a solution to sort this array/list.

Note :
Try to solve the problem in 'Single Scan'. ' Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains an Integer 'N' denoting the size of the array/list.

The second line of each test case contains 'N' space-separated Integers denoting the array/list.
Output format :
For each test case/query, print the sorted array/list(ARR) as space-separated Integers.

Output for every test case will be printed in a separate line.
Note:
You need to change in the given array/list itself. Hence, no need to return or print anything.
Constraints :
1 <= T <= 10
1 <= N <= (5 * (10 ^ 5))
0 <= ARR[i] <= 2

Where 'N' is the size of the given array/list.
And, ARR[i] denotes the i-th element in the array/list.

Time Limit: 1sec 
Sample Input 1 :
2
6
0 1 2 2 1 0
7
0 1 2 1 2 1 2
Sample Output 1 :
0 0 1 1 2 2
0 1 1 1 2 2 2
Sample Input 2 :
2
7
2 2 2 1 1 1 0
6
2 1 2 0 1 0
Sample Output 2 :
0 1 1 1 2 2 2
0 0 1 1 2 2
Hint

Can try to find the sorting algorithm of best time Complexity.

Approaches (3)
Sorting

Use any good sorting algorithm like Merge Sort, Quick Sort or inbuilt sorting function of different languages.

  • Sort the Array and just return.
Time Complexity

O(N*log(N)), where ‘N’ is the size of the array.

We are using inbuilt sort algorithm which has Overall Time Complexity O(N*log(N))

Space Complexity

O(1), As we are using constant space.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Sort 0 1 2
Full screen
Console