


For ‘arr’ = {1, 0, 0, 2, 1}.
‘Answer’ = {0, 0, 1, 1, 2}.
‘Answer’ should contain all 0s first, then all 1s and all 2s in the end.
The first line contains an integer ‘T’, denoting the number of test cases.
For each test case:
The first line contains an integer ‘N’, representing the size of the array ‘arr’.
The second line contains ‘N’ integers, denoting the elements of the array ‘arr’.
For each testcase, return an array ‘Answer’ which contains all the elements of ‘arr’ in sorted order.
1 <= ‘T’ <= 10^5
1 <= ‘N’ <= 10^5
0 <= ‘arr[i]’ <= 2
Sum of ‘N’ for all testcases <= 10^5
Time Limit: 1 sec
We can maintain an array ‘count’ where ‘count[i]’ maintains the count of ‘i’ in ‘arr’. Then we can simply iterate through ‘count’ and push ‘i’ ‘count[i]’ times into ‘Answer’.
We can maintain 3 pointers ‘low’, ‘mid’ and ‘high’. We divide the array into four sections, 0 to ‘low-1’ containing 0s, ‘low’ to ‘mid-1’ containing 1s, ‘mid’ to ‘high-1’ which is unsorted and finally ‘high’ to ‘N-1’ containing 2s. The key idea behind this approach is to send all the 0’s to range [0,’low-1’], all the 1s to range [‘low’,’mid-1’] and all the 2s to range [‘high’,’N-1’].The range [‘mid’, ‘high-1’] contains unprocessed elements. We iterate through ‘arr’ via ‘mid’ while ‘mid’ <= ‘high’. If ‘arr[mid]’ == ‘0’, we swap it with ‘arr[low]’ and increment ‘low’ and ‘mid’. If ‘arr[mid]’ == ‘1’ we increment ‘mid’. If the ‘arr[mid]’ == 2 we swap it with ‘arr[high]’ an ‘high’ (as after the swap ‘arr[mid]’ is unprocessed.).