Minimum sum of two numbers formed from digits of an array

31 Mar, 2022
Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers. Examples :  
Input: [6, 8, 4, 5, 2, 3]
Output: 604
The minimum sum is formed by numbers 
358 and 246

Input: [5, 3, 0, 7, 4]
Output: 82
The minimum sum is formed by numbers 
35 and 047 
 
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 ans so on..The idea is to sort the array in increasing order and build two numbers by alternating picking digits from the array. So first number is formed by digits present in odd positions in the array and second number is formed by digits from even positions in the array. Finally, we return the sum of first and second number.Below is the implementation of above idea.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum sum of two numbers// formed from digits of the array.#include <bits/stdc++.h>using namespace std; // Function to find and return minimum sum of// two numbers formed from digits of the array.int solve(int arr[], int n){    // sort the array    sort(arr, arr + n);     // let two numbers be a and b    int a = 0, b = 0;    for (int i = 0; i < n; i++)    {        // fill a and b with every alternate digit        // of input array        if (i & 1)            a = a*10 + arr[i];        else            b = b*10 + arr[i];    }     // return the sum    return a + b;} // Driver codeint main(){    int arr[] = {6, 8, 4, 5, 2, 3};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Sum is " << solve(arr, n);    return 0;}
// Java program to find minimum sum of two numbers// formed from digits of the array.import java.util.Arrays; class GFG {         // Function to find and return minimum sum of    // two numbers formed from digits of the array.    static int solve(int arr[], int n)    {                 // sort the array        Arrays.sort(arr);             // let two numbers be a and b        int a = 0, b = 0;        for (int i = 0; i < n; i++)        {                         // fill a and b with every alternate            // digit of input array            if (i % 2 != 0)                a = a * 10 + arr[i];            else                b = b * 10 + arr[i];        }             // return the sum        return a + b;    }         //driver code    public static void main (String[] args)    {        int arr[] = {6, 8, 4, 5, 2, 3};        int n = arr.length;                 System.out.print("Sum is "                          + solve(arr, n));    }} //This code is contributed by Anant Agarwal.
# Python3 program to find minimum sum of two# numbers formed from digits of the array. # Function to find and return minimum sum of# two numbers formed from digits of the array.def solve(arr, n):     # sort the array    arr.sort()     # let two numbers be a and b    a = 0; b = 0    for i in range(n):             # Fill a and b with every alternate        # digit of input array        if (i % 2 != 0):            a = a * 10 + arr[i]        else:            b = b * 10 + arr[i]     # return the sum    return a + b # Driver codearr = [6, 8, 4, 5, 2, 3]n = len(arr)print("Sum is ", solve(arr, n)) # This code is contributed by Anant Agarwal.
// C# program to find minimum// sum of two numbers formed// from digits of the array.using System; class GFG{    // Function to find and return    // minimum sum of two numbers    // formed from digits of the array.    static int solve(int []arr, int n)    {        // sort the array        Array.Sort(arr);              // let two numbers be a and b        int a = 0, b = 0;        for (int i = 0; i < n; i++)        {            // fill a and b with every alternate digit            // of input array            if (i % 2 != 0)                a = a * 10 + arr[i];            else                b = b * 10 + arr[i];        }              // return the sum        return a + b;    }         // Driver code    public static void Main ()    {        int []arr = {6, 8, 4, 5, 2, 3};        int n = arr.Length;        Console.WriteLine("Sum is " + solve(arr, n));    }} // This code is contributed by Anant Agarwal.
<?php// PHP program to find minimum// sum of two numbers formed// from digits of the array. // Function to find and return// minimum sum of two numbers// formed from digits of the array.function solve($arr, $n){    // sort the array    sort($arr); sort($arr , $n);     // let two numbers be a and b    $a = 0; $b = 0;    for ($i = 0; $i < $n; $i++)    {        // fill a and b with every        // alternate digit of input array        if ($i & 1)            $a = $a * 10 + $arr[$i];        else            $b = $b * 10 + $arr[$i];    }     // return the sum    return $a + $b;} // Driver code$arr = array(6, 8, 4, 5, 2, 3);$n = sizeof($arr);echo "Sum is " , solve($arr, $n);     // This code is contributed by nitin mittal.?>
<script> // Javascript program to find minimum sum of two numbers// formed from digits of the array.     // Function to find and return minimum sum of    // two numbers formed from digits of the array.    function solve(arr, n)    {                   // sort the array        arr.sort();               // let two numbers be a and b        let a = 0, b = 0;        for (let i = 0; i < n; i++)        {                           // fill a and b with every alternate            // digit of input array            if (i % 2 != 0)                a = a * 10 + arr[i];            else                b = b * 10 + arr[i];        }               // return the sum        return a + b;    } // Driver Code         let arr = [6, 8, 4, 5, 2, 3];        let n = arr.length;                   document.write("Sum is "                          + solve(arr, n)); </script>
Output : 
Sum is 604
Method 2 (For Large Numbers) 
When we have to deal with very big numbers (as in the PRACTICE section of this question) the above approach will not work. The basic idea of approaching the question is the same as above, but instead of using numbers, we will use strings to handle sum.
To add two numbers given in form of the string, you can refer to this.
C++
Python3
Javascript
#include <bits/stdc++.h>using namespace std; string solve(int arr[], int n){    // code here    // sorting of array O(nlogn)    sort(arr, arr + n);    // Two String for storing our two minimum numbers    string a = "", b = "";    // string string alternatively    for (int i = 0; i < n; i += 2)    {        a += (arr[i] + '0');    }    for (int i = 1; i < n; i += 2)    {        b += (arr[i] + '0');    }    int j = a.length() - 1;    int k = b.length() - 1;    // as initial carry is zero    int carry = 0;    string ans = "";    while (j >= 0 && k >= 0)    {        int sum = 0;        sum += (a[j] - '0') + (b[k] - '0') + carry;        ans += to_string(sum % 10);        carry = sum / 10;        j--;        k--;    }    // if string b is over and string a is left    // here we dont need to put here while condition    // as it would run at max one time. Because the difference    // between both the strings could be at max 1.    while (j >= 0)    {        int sum = 0;        sum += (a[j] - '0') + carry;        ans += to_string(sum % 10);        carry = sum / 10;        j--;    }    // if string a is over and string b is left    while (k >= 0)    {        int sum = 0;        sum += (b[k] - '0') + carry;        ans += to_string(sum % 10);        carry = sum / 10;        k--;    }    // if carry is left    if (carry)    {        ans += to_string(carry);    }    // to remove leading zeroes as they will be ahead of our sum    while (!ans.empty() and ans.back() == '0')        ans.pop_back();    // reverse our final string because we were storing sum from left to right    reverse(ans.begin(), ans.end());    return ans;} //  Driver Code Starts.int main(){    int arr[] = {6, 8, 4, 5, 2, 3};    int n = sizeof(arr) / sizeof(arr[0]);    cout << "Sum is " << solve(arr, n);    return 0;} //  Driver Code Ends
# Python code for the approachdef solve(arr, n):     # sorting of array O(nlogn)    arr.sort()         # Two String for storing our two minimum numbers    a,b = "",""         # string string alternatively    for i in range(0,n,2):        a += str(arr[i])     for i in range(1,n,2):        b += str(arr[i])     j = len(a) - 1    k = len(b) - 1    # as initial carry is zero    carry = 0    ans = ""    while (j >= 0 and k >= 0):        sum = 0        sum += (ord(a[j]) - ord('0') + ord(b[k]) - ord('0')) + carry        ans += str(sum % 10)        carry = sum // 10        j -= 1        k -= 1             # if string b is over and string a is left    # here we dont need to put here while condition    # as it would run at max one time. Because the difference    # between both the strings could be at max 1.    while (j >= 0):        sum = 0        sum += (a[j] - '0') + carry        ans += (sum % 10).toString()        carry = sum // 10        j -= 1             # if string a is over and string b is left    while (k >= 0):        sum = 0        sum += ord(b[k]) - ord('0') + carry        ans += str(sum % 10)        carry = (sum // 10)        k -= 1     # if carry is left    if (carry):        ans += str(carry)         # to remove leading zeroes as they will be ahead of our sum    while (len(ans) and ans[len(ans) - 1] == '0'):        ans.pop()             # reverse our final string because we were storing sum from left to right    ans = ans[::-1]    return ans #  Driver Codearr = [6, 8, 4, 5, 2, 3]n = len(arr)print("Sum is " + solve(arr, n)) # This code is contributed by shinjanpatra
<script> function solve(arr, n){     // sorting of array O(nlogn)    arr.sort();         // Two String for storing our two minimum numbers    let a = "", b = "";         // string string alternatively    for (let i = 0; i < n; i += 2)    {        a += arr[i];    }    for (let i = 1; i < n; i += 2)    {        b += arr[i];    }    let j = a.length - 1;    let k = b.length - 1;    // as initial carry is zero    let carry = 0;    let ans = "";    while (j >= 0 && k >= 0)    {        let sum = 0;        sum += (a.charCodeAt(j) - '0'.charCodeAt(0)) + (b.charCodeAt(k) - '0'.charCodeAt(0)) + carry;        ans += (sum % 10).toString();        carry = Math.floor(sum / 10);        j--;        k--;    }    // if string b is over and string a is left    // here we dont need to put here while condition    // as it would run at max one time. Because the difference    // between both the strings could be at max 1.    while (j >= 0)    {        let sum = 0;        sum += (a[j] - '0') + carry;        ans += (sum % 10).toString();        carry = Math.floor(sum / 10);        j--;    }    // if string a is over and string b is left    while (k >= 0)    {        let sum = 0;        sum += (b.charCodeAt(k) - '0'.charCodeAt(0)) + carry;        ans += (sum % 10).toString();        carry = Math.floor(sum / 10);        k--;    }    // if carry is left    if (carry)    {        ans += carry.toString();    }         // to remove leading zeroes as they will be ahead of our sum    while (ans.length && ans[ans.length-1] == '0')        ans.pop();             // reverse our final string because we were storing sum from left to right    ans = ans.split('').reverse().join('');    return ans;} //  Driver Code Starts. let arr = [6, 8, 4, 5, 2, 3];let n = arr.length;document.write("Sum is " + solve(arr, n)); // This code is contributed by shinjanpatra</script>
Sum is 604
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
souravghosh0416
aroraritesh95
shinjanpatra
number-digits
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.