![]() |
VOOZH | about |
Given an array arr[] of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed using all digits of the array.
Note: We need to return the minimum possible sum as a string.
Examples:
Input: arr[] = [6, 8, 4, 5, 2, 3, 0]
Output: "604"
Explanation: The minimum sum is formed by numbers 0358 and 246.Input: arr[] = [5, 3, 0, 7, 4]
Output: "82"
Explanation: The minimum sum is formed by numbers 35 and 047.
Table of Content
A minimum number will be formed from set of digits when smallest digit appears at most significant position and next smallest digit appears at next most significant position and so on. The idea is to first sort the digits in increasing order so that smaller digits come first. Then, we form two numbers by alternately picking digits from the sorted array. This ensures that the smallest digits are placed at the most significant positions of both numbers, keeping them balanced in length and minimizing their sum.
Illustration:
604
This approach uses a count array to store the frequency of digits from 0 to 9, avoiding the need for sorting. By traversing the count array from smallest to largest digit and alternately assigning digits to two numbers while avoiding leading zeros, we can efficiently construct the two numbers with minimum sum in linear time.
Algorithm:
s1 and s2. 604