Skip to content
Related Articles

Related Articles

Minimum sum of two numbers formed from digits of an array

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 29 Oct, 2022
Improve Article
Save Article

Given an array of digits (values are from 0 to 9), the task is to find the minimum possible sum of two numbers formed from digits of the array. Please note that all digits of the given array must be used to form the two numbers. 
 

Examples: 

Input: {6, 8, 4, 5, 2, 3}
Output: 604
Explanation: The minimum sum is formed by numbers 358 and 246

Input: {5, 3, 0, 7, 4}
Output: 82
Explanation: The minimum sum is formed by numbers 35 and 047 

Recommended Practice

Minimum sum of two numbers formed from digits of an array using Sorting:

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 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.

Follow the given steps to solve the problem:

  • Sort the array in increasing order
  • Declare two variables a and b, representing the two numbers to be formed
  • Traverse the array and if the index is odd then add this element into a, else add it to b
  • Return the sum of two variables (a + b)

Below is the Implementation of the above approach:
 

C




// C program to find minimum sum of two numbers
// formed from digits of the array.
 
#include <stdio.h>
#include <stdlib.h>
 
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
 
// 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
    qsort(arr, N, sizeof(int), cmpfunc);
 
    // 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's code
int main()
{
    int arr[] = { 6, 8, 4, 5, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printf("Sum is %d", solve(arr, N));
    return 0;
}

C++




// 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's code
int main()
{
    int arr[] = { 6, 8, 4, 5, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << "Sum is " << solve(arr, N);
    return 0;
}

Java




// 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's 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




# 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's code
if __name__ == '__main__':
    arr = [6, 8, 4, 5, 2, 3]
    N = len(arr)
 
    # Function call
    print("Sum is ", solve(arr, N))
 
    # This code is contributed by Anant Agarwal.

C#




// 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's code
    public static void Main()
    {
        int[] arr = { 6, 8, 4, 5, 2, 3 };
        int N = arr.Length;
 
        // Function call
        Console.WriteLine("Sum is " + solve(arr, N));
    }
}
 
// This code is contributed by Anant Agarwal.

PHP




<?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's code
$arr = array(6, 8, 4, 5, 2, 3);
$N = sizeof($arr);
 
// Function call
echo "Sum is " , solve($arr, $N);
     
// This code is contributed by nitin mittal.
?>

Javascript




// 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));

Output

Sum is 604

Time Complexity: O(Nlog2N) because of arr.sort()  
Auxiliary Space: O(1)

Minimum sum of two numbers formed from digits of an array for large numbers using Strings:

The basic idea of approaching the question is the same as above, but instead of using numbers, strings will be used to handle sum of two large numbers

Follow the given steps to solve the problem:

  • Sort the array in increasing order
  • Declare two strings a and b, representing the two numbers to be formed
  • Traverse the array and if the index is odd then add this element into string a, else add it to the string b
  • Return the sum of two strings, in the form of a string

Below is the Implementation of the above approach:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
string solve(int arr[], int n)
{
 
    sort(arr, arr + n);
 
    // Two String for storing our two minimum numbers
    string a = "", b = "";
 
    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's Code
int main()
{
    int arr[] = { 6, 8, 4, 5, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << "Sum is " << solve(arr, N);
    return 0;
} //  Driver Code Ends

Java




// Java code for the above approach
 
import java.util.Arrays;
import java.util.Collections;
 
class Main {
 
    public static String reverseString(String str)
    {
 
        StringBuilder sb = new StringBuilder(str);
        sb.reverse();
        return sb.toString();
    }
 
    public static String solve(int[] arr, int N)
    {
 
        Arrays.sort(arr);
 
        // Two String for storing our two minimum numbers
        String a = "", b = "";
 
        for (int i = 0; i < N; i += 2) {
            a += Integer.toString(arr[i]);
        }
        for (int i = 1; i < N; i += 2) {
            b += Integer.toString(arr[i]);
        }
 
        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.charAt(j) - '0') + (b.charAt(k) - '0')
                   + carry;
            int x = sum % 10;
            ans += Integer.toString(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.charAt(j) - '0') + carry;
            ans += Integer.toString(sum % 10);
            carry = sum / 10;
            j--;
        }
 
        // If string a is over and string b is left
        while (k >= 0) {
            int sum = 0;
            sum += (b.charAt(k) - '0') + carry;
            ans += Integer.toString(sum % 10);
            carry = sum / 10;
            k--;
        }
        // if carry is left
        if (carry != 0) {
            ans += Integer.toString(carry);
        }
 
        // to remove leading zeroes as they will be ahead of
        // our sum
        while (ans.isEmpty() == false
               && ans.charAt(ans.length() - 1) == '0')
            ans = ans.substring(0, ans.length() - 1);
 
        // reverse our final string because we were storing
        // sum from left to right
        ans = reverseString(ans);
        return ans;
    }
 
    // driver's code
    public static void main(String[] args)
    {
        int[] arr = { 6, 8, 4, 5, 2, 3 };
        int N = arr.length;
 
        // Function call
        System.out.print("Sum is " + solve(arr, N));
    }
}
 
// This code is contributed by Chhavi

Python3




# Python3 code for the approach
 
 
def solve(arr, N):
 
    arr.sort()
 
    # Two String for storing our two minimum numbers
    a, b = "", ""
 
    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's Code
if __name__ == '__main__':
    arr = [6, 8, 4, 5, 2, 3]
    N = len(arr)
 
    # Function call
    print("Sum is " + solve(arr, N))
 
# This code is contributed by shinjanpatra

Javascript




function solve(arr, N)
{
 
     
    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

Output

Sum is 604

Time complexity: O(Nlog2N) because we are sorting the given array.
Auxiliary Space: O(N) 

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!