Array ( [0] => [1] => questions [2] => Arrays [3] => Constraint-Sort ) Arrays | Constraint Sort | THE INQUISITIVE





Constraint Sort

LEVEL:Beginner

Description

Given an array of integers consisting of 0’s 1’s 2’s. You have to sort the array.

Input Format

First line contains the size of the first array. Next line contains the m integers separated by the spaces.

Output Format

Print the sorted array


Example 1:

Input
6
1 0 2 2 1 0
Output
0 0 1 1 2 2
Example 2:

Input
8
2 2 1 0 0 1 1 0
Output
0 0 0 1 1 1 2 2	
Example 3:

Input
4
1 1 0 2
Output
0 1 1 2

oops

Login to see Discussion




Approach

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.

oops

Login to see Solution