Given an array of integers “ARR” in which value of each element is between 0 and 9(both inclusive), You are supposed to construct two numbers by concatenating the elements of ARR and find the minimum possible sum of two numbers formed using the elements of the array.
Note: Each element of the given array must be a part of exactly one number.
The first line of input contains an integer 'T' representing the number of test cases.
The first line of each test case contains one integer ‘N’ denoting the number of elements in the array.
The second line of each test case contains N space-separated integers denoting the elements of the array ARR.
Output Format :
For each test case, on a separate line, output one integer - the minimum possible sum of numbers.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^4
0 <= A[i] <= 9
Where ‘T’ is the number of test cases, ‘N’ is the size of the given array, and ‘ARR[i]’ denotes the ith element of the array.
Time limit: 1 sec
2
6
4 0 3 7 6 5
5
6 1 2 4 3
403
160
For the first test case, the minimum sum is formed by numbers 357 and 046, and their sum is 403.
For the second test case, the minimum sum is formed by numbers 24 and 136, and their sum is 160.
2
7
9 2 3 5 0 7 2
3
9 2 2
496
31
Can you solve it greedily?
The idea is to sort the array in ascending order and then concatenate the array elements alternatively to the first and the second number. So, the first number is formed by the elements present in the even position and the second number is formed by the elements present in the odd position. The sum of the first and the second number will be the minimum sum.
The algorithm is as follows :
O(NlogN), where N is the size of the given array.
Here, we are first sorting the elements in the array, which takes O(NlogN) time, and then we are iterating through the array to calculate the firstNum and secondNum, and then we are adding the two string numbers that will take O(N) time. Hence, the overall time complexity is O(NlogN).
O(N), where N is the size of the given array.
We are using the string ‘firstNum’, ‘secondNum’, both of which will have length ‘N’/2. Hence, the overall space complexity is O(N).