The Wayback Machine - https://web.archive.org/web/20250102133730/https://www.geeksforgeeks.org/minimum-sum-two-numbers-formed-digits-array/
Open In App

Minimum sum of two numbers formed from digits of an array

Last Updated : 13 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of digits (values are from 0 to 9), the task is to 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.

Approach:

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 the first number by digits present in odd positions and second number by digits from even positions in the array. So, that the first two smallest digits are placed in the most significant positions of both numbers, the next two smallest digits are placed in the second most significant positions, and this pattern continues for the remaining digits.

Illustration:


C++
// C++ program to find minimum sum of two numbers
// formed from digits of the array using sorting

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// Function to add two strings and return the result
string addString(string &s1, string &s2) {
    int i = s1.length() - 1;
    int j = s2.length() - 1;

    // initial carry is zero
    int carry = 0;

    // we will calculate and store the
    // resultant sum in reverse order in res
    string res = "";
    while (i >= 0 || j >= 0 || carry > 0) {
        int sum = carry;
        if (i >= 0)
            sum += (s1[i] - '0');

        if (j >= 0)
            sum += (s2[j] - '0');

        res.push_back(sum % 10 + '0');
        carry = sum / 10;
        i--;
        j--;
    }

    // remove leading zeroes which are currently
    // at the back due to reversed string res
    while (!res.empty() && res.back() == '0')
        res.pop_back();

    // reverse our final string
    reverse(res.begin(), res.end());

    return res;
}

// Function to find and return minimum sum of
// two numbers formed from digits of the array.
string minSum(vector<int> &arr) {
    sort(arr.begin(), arr.end());

    // Two String for storing the two minimum numbers
    string s1 = "", s2 = "";

    for (int i = 0; i < arr.size(); i++) {
        if (i % 2 == 0)
            s1.push_back(arr[i] + '0');
        else
            s2.push_back(arr[i] + '0');
    }

    return addString(s1, s2);
}

int main() {
    vector<int> arr = {6, 8, 4, 5, 2, 3, 0};

    cout << minSum(arr);
    return 0;
}
Java
// Java program to find minimum sum of two numbers
// formed from digits of the array using sorting

import java.util.*;

class GfG {

    // Function to add two strings and return the result
    static String addString(StringBuilder s1, StringBuilder s2) {
        int i = s1.length() - 1;
        int j = s2.length() - 1;

        // initial carry is zero
        int carry = 0;

        // we will calculate and store the 
        // resultant sum in reverse order in res
        StringBuilder res = new StringBuilder();
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;
            if (i >= 0)
                sum += (s1.charAt(i) - '0');

            if (j >= 0)
                sum += (s2.charAt(j) - '0');

            res.append(sum % 10);
            carry = sum / 10;
            i--;
            j--;
        }

        // remove leading zeroes which are currently
        // at the back due to reversed string res
        while (res.length() > 0 && res.charAt(res.length() - 1) == '0')
            res.deleteCharAt(res.length() - 1);

        // reverse our final string 
        res.reverse();

        return res.toString();
    }

    // Function to find and return minimum sum of
    // two numbers formed from digits of the array.
    static String minSum(int[] arr) {
        Arrays.sort(arr);

        // Two String for storing the two minimum numbers
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();

        for (int i = 0; i < arr.length; i++) {
            if (i % 2 == 0)
                s1.append(arr[i]);
            else
                s2.append(arr[i]);
        }

        return addString(s1, s2);
    }

    public static void main(String[] args) {
        int[] arr = {6, 8, 4, 5, 2, 3, 0};
        
        System.out.println(minSum(arr));
    }
}
Python
# Python program to find minimum sum of two numbers
# formed from digits of the array using sorting

# Function to add two numbers and return the result
def addNumbers(l1, l2):
    i = len(l1) - 1
    j = len(l2) - 1

    # initial carry is zero
    carry = 0

    # we will calculate and store the 
    # resultant sum in reverse order in res
    res = []
    while i >= 0 or j >= 0 or carry > 0:
        total = carry
        if i >= 0:
            total += l1[i]
        
        if j >= 0:
            total += l2[j]
        
        res.append(str(total % 10))
        carry = total // 10
        i -= 1
        j -= 1

    # remove leading zeroes which are currently
    # at the back due to reversed string res
    while len(res) > 0 and res[-1] == '0':
        res.pop()

    # reverse our final result
    res = res[::-1]
    return ''.join(res)

# Function to find and return minimum sum of
# two numbers formed from digits of the array.
def minSum(arr):
    arr.sort()

    # Two Lists for storing the two minimum numbers
    l1 = []
    l2 = []

    for i in range(len(arr)):
        if i % 2 == 0:
            l1.append(arr[i])
        else:
            l2.append(arr[i])

    return addNumbers(l1, l2)

if __name__ == '__main__':
    arr = [6, 8, 4, 5, 2, 3, 0]

    print(minSum(arr))
C#
// C# program to find minimum sum of two numbers
// formed from digits of the array using sorting

using System;
using System.Text;

class GfG {
  
    // Function to add two strings and return the result
    static string addString(StringBuilder s1, StringBuilder s2) {
        int i = s1.Length - 1;
        int j = s2.Length - 1;

        // initial carry is zero
        int carry = 0;

        // we will calculate and store the 
        // resultant sum in reverse order in res
        StringBuilder res = new StringBuilder();
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;
            if (i >= 0)
                sum += (s1[i] - '0');

            if (j >= 0)
                sum += (s2[j] - '0');

            res.Append(sum % 10);
            carry = sum / 10;
            i--;
            j--;
        }

        // remove leading zeroes which are currently
        // at the back due to reversed string res
        while (res.Length > 0 && res[res.Length - 1] == '0')
            res.Length--;

        // reverse our final string 
        // Convert to char array, reverse and then create a new string
        char[] resArray = res.ToString().ToCharArray();
        Array.Reverse(resArray);
        return new string(resArray);
    }

    // Function to find and return minimum sum of
    // two numbers formed from digits of the array.
    static string minSum(int[] arr) {
        Array.Sort(arr);

        // Two String for storing the two minimum numbers
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();

        for (int i = 0; i < arr.Length; i++) {
            if (i % 2 == 0)
                s1.Append(arr[i]);
            else
                s2.Append(arr[i]);
        }

        return addString(s1, s2);
    }

    static void Main(string[] args) {
        int[] arr = { 6, 8, 4, 5, 2, 3, 0 };
        Console.WriteLine(minSum(arr));
    }
}
JavaScript
// JavaScript program to find minimum sum of two numbers
// formed from digits of the array using sorting

// Function to add two lists and return the result
function addNumbers(l1, l2) {
    let i = l1.length - 1;
    let j = l2.length - 1;

    // initial carry is zero
    let carry = 0;

    // we will calculate and store the 
    // resultant sum in reverse order in res
    let res = [];
    while (i >= 0 || j >= 0 || carry > 0) {
        let sum = carry;
        if (i >= 0)
            sum += l1[i] - '0';

        if (j >= 0)
            sum += l2[j] - '0';

        res.push(sum % 10);
        carry = Math.floor(sum / 10);
        i--;
        j--;
    }

    // remove leading zeroes which are currently
    // at the back due to reversed list res
    while (res.length > 0 && res[res.length - 1] === 0)
        res.pop();

    // reverse our final list and convert it to a string
    return res.reverse().join('');
}

// Function to find and return minimum sum of
// two numbers formed from digits of the array.
function minSum(arr) {
    arr.sort((a, b) => a - b);

    // Two lists for storing the two minimum numbers
    let l1 = [], l2 = [];

    for (let i = 0; i < arr.length; i++) {
        if (i % 2 === 0)
            l1.push(arr[i]);
        else 
            l2.push(arr[i]);
    }

    return addNumbers(l1, l2);
}

// Driver Code
let arr = [6, 8, 4, 5, 2, 3, 0];
console.log(minSum(arr));

Output
604

Time Complexity: O(n*logn) as we are sorting the input array.
Auxiliary Space: O(n) to store the result.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg