Spider Man needs to retrieve a secret file stored in the computer of Dr. Octavius. He finds a clue to the password, but since he is running short on time, he asks you for help. Following is the clue provided-
Given ‘N’ DIGITS valued from 0 to 9, the password is the minimum possible sum of two numbers formed by using all the DIGITS only once.
For example - For DIGITS = [4, 3, 2, 7, 1, 9], the minimum sum is 385 which is obtained by adding numbers 137 and 249.
Can you help Spider Man find the password?
Note - The number of DIGITS is always greater than or equal to 2. Hence, the answer will always exist.
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.
The first line of each test case contains a single integer ‘N’ denoting the number of digits.
The second line of each test case contains ‘N’ single space-separated non-negative integers representing the digits.
Output Format :
For each test case, print the password.
Print the output of each test case in a separate line.
Note :
You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 100
2 <= N <= 5000
0 <= DIGITS[i] <= 9
Where ‘N’ is the number of digits
Time Limit: 1sec
2
4
1 2 9 8
3
1 1 0
47
2
For the first test case, the password is 47 which is the minimum sum obtained by adding numbers 18 and 29.
For the second test case, the password is 12 which is the minimum sum obtained by adding numbers 01 and 1.
1
2
2 8
10
Think of rearranging the DIGITS in a way that helps in finding those two numbers easily.
To find the two numbers that add up to the minimum sum, we take into account the following points -
Here is the complete approach -
O(NlogN), where N denotes the number of digits provided.
Sorting the digits takes O(NlogN) time. We then traverse all digits to find the two numbers and calculate their sum which takes O(N) time. Thus, the overall time complexity is O(NlogN).
O(1), constant space is used.