Sort an array of 0s, 1s and 2s

You have been given an array/list ARR consisting of ‘N’ elements. Each element in the array is either 0, 1 or 2.

Now, your task is to sort this array/list in increasing order. For example, if ARR = [0, 2, 1, 1], then after sorting ARR must look like [0, 1, 1, 2].

Input Format:
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first line of each test case contains a positive integer ‘N’ which represents the length of the array/list.

The second line of each test case contains ‘N’ single space-separated integers representing the elements of the array/list.
Output Format:
For each test case, the only line of output will print ‘N’ single space-separated integers of the sorted array/list.  

Print the output of each test case in a separate line.

Note:

You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 100
1 <= N <= 5000
0 <= ARR[i] <= 2

Time limit: 1 sec
CodingNinjas
author
2y

The simple approach is to simply count the number of 0’s, 1’s, and 2’s. Then, place all 0’s at the beginning of the array followed by 1’s and 2's. The time complexity of this approach would be O(n) an...read more

CodingNinjas
author
2y
NAIVE APPROACH

Simply, we will sort the array.

Space Complexity: O(1)Explanation:

O(1), i.e. constant space complexity.

Since we are not using any extra space. Hence, the space complexity is constant.

T...read more
CodingNinjas
author
2y
COUNT 0, 1 and 2

A two-pass algorithm can easily solve the problem. We will count the number of 0s, 1s and 2s in the array/list.

Then, we will overwrite the array with the total number of 0s, followed...read more

CodingNinjas
author
2y
THREE-POINTER APPROACH

We can sort the array in one-pass by maintaining three positional pointers ‘zeroPos’, ‘onePos’ and ‘twoPos’ initialised to 0, 0 and N-1, respectively.

Here, ‘zeroPos’ represents ...read more

Add answer anonymously...
VMware Software 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
Get AmbitionBox app

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