You’re given an array of ‘N’ integers. Your task is to find all those array elements which contain 1, 2, and 3 in their digits and then print them in ascending order. If no element has 1,2 and 3 in its digits, then print ‘-1’.
Example :12345 satisfies the condition since it has all ‘1’, ‘2’, and ‘3’ in its digits, but 124 doesn’t satisfy the condition since it only has ‘1’ and ‘2’ but not ‘3’ in its digits.
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains an integer N, the number of elements in the array.
The next line of each test case contains N space-separated integers, denoting the array elements.
Output Format :
For every test case, the only output line contains an array containing the elements with ‘1’,’2’, and ‘3’ in their digits in ascending order.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
Note:
You have to return an array containing elements with ‘1’,’2’, and ‘3’ in their digits in ascending order. If there is no such element containing ‘1’, ‘2’, and ‘3’ in its digits, return an empty array.
1 <= T <= 5
1 <= N <= 10^5
1 <= arr[i] <= 10^9
Time limit: 1 sec
1
5
123 1234 12345 1245 1230
123 1230 1234 12345
Out of the given array elements, only 1245 doesn’t have the digit ‘3’. Hence we’ll print all other elements in ascending order.
2
4
321 123 131 432
3
124 324 134
123 321
-1
Check if the elements contain the digits.
We will create an “answer” array to store the elements with ‘1’, ‘2’, and ‘3’ in their digits. For all the array elements, we will check if the element contains ‘1’, ‘2’, and ‘3’, and if this condition is true, then we will push this element into our answer array.
Algorithm :
O(N * log(N)), where ‘N’ is the number of elements in the array.
We are traversing an array of N elements that will take O(N) time, and containsNumberHelper() will take constant time. Also, we will be sorting the ‘answer’ array which will take O(N * log(N)) time. Hence, the final time complexity will be O(N) + O(N * log(N))= O(N * log(N)).
O(N), where ‘N’ is the number of elements in the array.
As we are making an answer array of size ‘N.’ Hence, the final space complexity will be O(N).