Array ( [0] => [1] => questions [2] => Strings [3] => Constraint-Sort )
Given an array of integers consisting of 0’s 1’s 2’s. You have to sort the array.
First line contains the size of the first array. Next line contains the m integers separated by the spaces.
Print the sorted array
6 1 0 2 2 1 0
0 0 1 1 2 2
8 2 2 1 0 0 1 1 0
0 0 0 1 1 1 2 2
4 1 1 0 2
0 1 1 2
Login to see Discussion
Approach1: Sort
Step-i) Sort the given array.
Step-ii) Return the sorted array to saggregate 0’s, 1’s and 2’s.
Time Complexity: O(n logn)
Space Complexity: O(n)
Approach2:
Step-i) Initialize 3 variables zero, one, two with 0.
Step-ii) Use 3 variables to count the no. of zeroes ones and twos.
Step-iii) Create another array of same size.
Step-iv) Store the element of the count of the 3 variables in the new array.
Step-v) Return the new array.
Time Complexity: O(n)
Space Complexity: O(n)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution