Open In App

Minimum sum of two numbers formed from digits of an array

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 
Recommended Practice

Since we want to minimize the sum of two numbers to be formed, we must divide all digits in two halves and assign half-half digits to them. We also need to make sure that the leading digits are smaller. 

We build a Min Heap with the elements of the given array, which takes O(n) worst time. Now we retrieve min values (2 at a time) of array, by polling from the Priority Queue and append these two min values to our numbers, till the heap becomes empty, i.e., all the elements of array get exhausted. We return the sum of two formed numbers, which is our required answer. Overall complexity is O(nlogn) as push() operation takes O(logn) and it’s repeated n times. 

Implementation:

C++




// C++ program to find minimum sum of two numbers
// formed from all digits in a given array.
#include<bits/stdc++.h>
using namespace std;
 
// Returns sum of two numbers formed
// from all digits in a[]
int minSum(int arr[], int n)
{
    // min Heap
    priority_queue <int, vector<int>, greater<int> > pq;
 
    // to store the 2 numbers formed by array elements to
    // minimize the required sum
    string num1, num2;
 
    // Adding elements in Priority Queue
    for(int i=0; i<n; i++)
        pq.push(arr[i]);
 
    // checking if the priority queue is non empty
    while(!pq.empty())
    {
        // appending top of the queue to the string
        num1+=(48 + pq.top());
        pq.pop();
        if(!pq.empty())
        {
            num2+=(48 + pq.top());
            pq.pop();
        }
    }
 
    // converting string to integer
    int a = atoi(num1.c_str());
    int b = atoi(num2.c_str());
 
    // returning the sum
    return a+b;
}
 
int main()
{
    int arr[] = {6, 8, 4, 5, 2, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout<<minSum(arr, n)<<endl;
    return 0;
}
// Contributed By: Harshit Sidhwa


Java




// Java program to find minimum sum of two numbers
// formed from all digits in a given array.
import java.util.PriorityQueue;
 
class MinSum
{
    // Returns sum of two numbers formed
    // from all digits in a[]
    public static long solve(int[] a)
    {
        // min Heap
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
 
        // to store the 2 numbers formed by array elements to
        // minimize the required sum
        StringBuilder num1 = new StringBuilder();
        StringBuilder num2 = new StringBuilder();
 
        // Adding elements in Priority Queue
        for (int x : a)
            pq.add(x);
 
        // checking if the priority queue is non empty
        while (!pq.isEmpty())
        {
            num1.append(pq.poll()+ "");
            if (!pq.isEmpty())
                num2.append(pq.poll()+ "");
        }
 
        // the required sum calculated
        long sum = Long.parseLong(num1.toString()) +
                   Long.parseLong(num2.toString());
 
        return sum;
    }
 
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = {6, 8, 4, 5, 2, 3};
        System.out.println("The required sum is "+ solve(arr));
    }
}


Python3




# Python3 program to find minimum
# sum of two numbers formed from
# all digits in a given array.
from queue import PriorityQueue
 
# Returns sum of two numbers formed
# from all digits in a[]
def solve(a):
     
    # min Heap
    pq = PriorityQueue()
     
    # To store the 2 numbers
    # formed by array elements to
    # minimize the required sum
    num1 = ""
    num2 = ""
 
    # Adding elements in
    # Priority Queue
    for x in a:
        pq.put(x)
 
    # Checking if the priority
    # queue is non empty
    while not pq.empty():
        num1 += str(pq.get())
        if not pq.empty():
            num2 += str(pq.get())   
 
    # The required sum calculated
    sum = int(num1) + int(num2)
     
    return sum
     
# Driver code
if __name__=="__main__":
     
    arr = [ 6, 8, 4, 5, 2, 3 ]
    print("The required sum is ", solve(arr))
 
# This code is contributed by rutvik_56


C#




// C# program to find minimum sum of two numbers
// formed from all digits in a given array.
using System;
using System.Collections.Generic;
class GFG
{
     
    // Returns sum of two numbers formed
    // from all digits in a[]
    public static long solve(int[] a)
    {
       
        // min Heap
        List<int> pq = new List<int>();
  
        // to store the 2 numbers formed by array elements to
        // minimize the required sum
        string num1 = "";
        string num2 = "";
  
        // Adding elements in Priority Queue
        foreach(int x in a)
            pq.Add(x);
             
        pq.Sort();
  
        // checking if the priority queue is non empty
        while (pq.Count > 0)
        {
            num1 = num1 + pq[0];
            pq.RemoveAt(0);
            if (pq.Count > 0)
            {
                num2 = num2 + pq[0];
                pq.RemoveAt(0);
            }
        }
  
        // the required sum calculated
        int sum = Int32.Parse(num1) + Int32.Parse(num2);
  
        return sum;
    }
     
  // Driver code
  static void Main()
  {
    int[] arr = {6, 8, 4, 5, 2, 3};
    Console.WriteLine("The required sum is "+ solve(arr));
  }
}
 
// This code is contributed by divyesh072019.


Javascript




<script>
 
// Javascript program to find minimum sum of two numbers
// formed from all digits in a given array.
     
    // Returns sum of two numbers formed
    // from all digits in a[]
    function solve(a)
    {
        // min Heap
        pq=[];
        // to store the 2 numbers formed by array elements to
        // minimize the required sum
        let num1="";
        let num2="";
         
        // Adding elements in Priority Queue
        for(let x=0;x<a.length;x++)
        {
            pq.push(a[x]);
        }
        pq.sort(function(a,b){return b-a;});
         
        // checking if the priority queue is non empty
        while(pq.length!=0)
        {
            num1+=pq.pop();
            if(pq.length!=0)
            {
                num2+=pq.pop();
            }
        }
        // the required sum calculated
        let sum=parseInt(num1)+parseInt(num2);
        return sum;
    }
    // Driver code
    let arr=[6, 8, 4, 5, 2, 3];
    document.write("The required sum is "+ solve(arr));
     
    // This code is contributed by avanitrachhadiya2155
     
</script>


Output

604

Time Complexity: O(N * log N)
Auxiliary Space: O(N)

Another method: We can follow another approach also like this, as we need two numbers such that their sum is minimum, then we would also need two minimum numbers. If we arrange our array in ascending order then we can two digits that will form the smallest numbers, 

e.g., 2 3 4 5 6 8, now we can get two numbers starting from 2 and 3. First part is done now. Moving forward we have to form such that they would contain small digits, i.e. pick digits alternatively from array extend your two numbers. 

i.e. 246, 358. Now if we see analyze this, then we can pick even indexed numbers for num1 and an odd number for num2.

Below is the implementation:

C++




// C++ program to find minimum sum of two numbers
// formed from all digits in a given array.
#include <bits/stdc++.h>
using namespace std;
 
// Returns sum of two numbers formed
// from all digits in a[]
int minSum(int a[], int n)
{
    // sort the elements
    sort(a, a + n);
    int num1 = 0;
    int num2 = 0;
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0)
            num1 = num1 * 10 + a[i];
        else
            num2 = num2 * 10 + a[i];
    }
    return num2 + num1;
}
 
// Driver code
int main()
{
    int arr[] = { 5, 3, 0, 7, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "The required sum is  " << minSum(arr, n)
         << endl;
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


C




// C program to find minimum sum of two numbers
// formed from all digits in a given array.
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
 
// Returns sum of two numbers formed
// from all digits in a[]
int minSum(int a[], int n)
{
 
    // sort the elements
    qsort(a, n, sizeof(int), cmpfunc);
    //     sort(a,a+n);
 
    int num1 = 0;
    int num2 = 0;
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0)
            num1 = num1 * 10 + a[i];
        else
            num2 = num2 * 10 + a[i];
    }
    return num2 + num1;
}
 
// Driver code
int main()
{
    int arr[] = { 5, 3, 0, 7, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("The required sum is %d", minSum(arr, n));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




import java.util.Arrays;
// Java program to find minimum sum of two numbers
// formed from all digits in a given array.
public class AQRQ {
 
    // Returns sum of two numbers formed
    // from all digits in a[]
    static int minSum(int a[], int n)
    {
        // sort the elements
        Arrays.sort(a);
        int num1 = 0;
        int num2 = 0;
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0)
                num1 = num1 * 10 + a[i];
            else
                num2 = num2 * 10 + a[i];
        }
        return num2 + num1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int arr[] = { 5, 3, 0, 7, 4 };
        int n = arr.length;
        System.out.println("The required sum is  "
                           + minSum(arr, n));
    }
}
 
// This code is contributed by Sania Kumari Gupta


Python3




# Python 3 program to find minimum
# sum of two numbers formed
# from all digits in an given array
 
# Returns sum of two numbers formed
# from all digits in a[]
def minSum(a, n):
     
    # sorted the elements
    a = sorted(a)
    num1, num2 = 0, 0
     
    for i in range(n):
        if i % 2 == 0:
            num1 = num1 * 10 + a[i]
        else:
            num2 = num2 * 10 + a[i]
     
    return num2 + num1    
     
# Driver code
arr = [5, 3, 0, 7, 4]
n = len(arr)
print("The required sum is",
             minSum(arr, n))
     
# This code is contributed
# by Mohit kumar 29


C#




// C# program to find minimum sum of two numbers
//formed from all digits in a given array.
 
using System;
 
public class GFG{
     
    //Returns sum of two numbers formed
    //from all digits in a[]
    static int minSum(int []a, int n){
     
    // sort the elements
    Array.Sort(a);
     
    int num1 = 0;
    int num2 = 0;
    for(int i = 0;i<n;i++){
        if(i%2==0)
            num1 = num1*10+a[i];
        else num2 = num2*10+a[i];
    }
    return num2+num1;
    }
 
    //Driver code
    static public void Main (){
        int []arr = {5, 3, 0, 7, 4};
        int n = arr.Length;
        Console.WriteLine("The required sum is " + minSum(arr, n));
    }
//This code is contributed by ajit.   
}


PHP




<?php
// PHP program to find minimum sum
// of two numbers formed from all
// digits in a given array.
 
// Returns sum of two numbers formed
// from all digits in a[]
function minSum($a, $n)
{
     
    // sort the elements
    sort($a);
     
    $num1 = 0;
    $num2 = 0;
    for($i = 0; $i < $n; $i++)
    {
        if($i % 2 == 0)
            $num1 = $num1 * 10 + $a[$i];
        else $num2 = $num2 * 10 + $a[$i];
    }
    return ($num2 + $num1);
}
 
// Driver code
$arr = array(5, 3, 0, 7, 4);
$n = sizeof($arr);
echo "The required sum is ",
     minSum($arr, $n), "\n";
 
// This Code is Contributed by ajit
?>


Javascript




<script>
 
    // JavaScript program to find minimum sum of two numbers
    // formed from all digits in a given array.
     
    // Returns sum of two numbers formed
    // from all digits in a[]
    function minSum(a, n){
 
        // sort the elements
        a.sort();
 
        let num1 = 0;
        let num2 = 0;
        for(let i = 0;i<n;i++){
            if(i%2==0)
                num1 = num1*10+a[i];
            else num2 = num2*10+a[i];
        }
        return num2+num1;
    }
     
    let arr = [5, 3, 0, 7, 4];
    let n = arr.length;
    document.write("The required sum is  " + minSum(arr, n));
     
</script>


Output

The required sum is  82

Time Complexity: O(N * log N)
Auxiliary Space: O(1)

 



Similar Reads

Minimum sum of two numbers formed from digits of an array in O(n)
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 the given array must be used to form the two numbers.Examples: Input: arr[] = {6, 8, 4, 5, 2, 3} Output: 604 246 + 358 = 604Input: arr[] = {5, 3, 0, 7, 4} Output: 82 Approach: A minimum number will be formed
6 min read
Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
Given three positive integers N, A, and B. The task is to count the numbers of length N containing only digits A and B and whose sum of digits also contains the digits A and B only. Print the answer modulo 109 + 7.Examples: Input: N = 3, A = 1, B = 3 Output: 1 Possible numbers of length 3 are 113, 131, 111, 333, 311, 331 and so on... But only 111 i
15 min read
Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
Given two integers N and K, the task is to count the numbers up to N digits such that no two zeros are adjacents and the range of digits are from 0 to K-1.Examples: Input: N = 2, K = 3 Output: 8 Explanation: There are 8 such numbers such that digits are from 0 to 2 only, without any adjacent 0s: {1, 2, 10, 11, 12, 20, 21, 22}Input: N = 3, K = 3 Out
12 min read
Count numbers formed by given two digit with sum having given digits
Given a, b and N(1 to 106). Task is to count the numbers formed by digits a and b exactly of a length N such that the sum of the digits of the number thus formed also contains digits a and b only. Since the count can be very large, print the count % 1000000007. Examples : Input : a = 1 b = 3 n = 3 Output : 1 Explanation : The only number is 111 of
15 min read
Number formed by deleting digits such that sum of the digits becomes even and the number odd
Given a non-negative number N, the task is to convert the number by deleting some digits of the number, such that the sum of the digits becomes even but the number is odd. In case there is no possible number, then print -1.Note: There can be multiple numbers possible for a given N.Examples: Input: N = 18720 Output: 17 Explanation: After Deleting 8,
5 min read
Minimum digits to be removed to make either all digits or alternating digits same
Given a numeric string str, the task is to find the minimum number of digits to be removed from the string such that it satisfies either of the below conditions: All the elements of the string are the same.All the elements at even position are same and all the elements at the odd position are same, which means the string is alternating with the equ
7 min read
Numbers with sum of digits equal to the sum of digits of its all prime factor
Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.Examples: Input: l = 2, r = 10 Output: 5 2, 3, 4, 5 and 7 are such numbers Input: l = 15, r = 22 Output: 3 17, 19 and 22 are such numbers As, 17 and 19 are already prime. Prime Factors
13 min read
Count numbers in given range such that sum of even digits is greater than sum of odd digits
Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits. Examples: Input : L=2 R=10 Output : 4 Numbers having the property that sum of even digits is greater than sum of odd digits are: 2, 4, 6, 8 Input : L=2 R=17 Outpu
14 min read
Count of numbers in range [L, R] having sum of digits of its square equal to square of sum of digits
Given two integers L and R, the task is to find the count of numbers in range [L, R] such that the sum of digits of its square is equal to the square of sum of its digits, Example: Input: L = 22, R = 22Output: 1Explanation: 22 is only valid number in this range as sum of digits of its square = S(22*22) = S(484) = 16 and square of sum of its digits
11 min read
Sum of numbers formed by consecutive digits present in a given string
Given a string S consisting of digits [0 - 9] and lowercase alphabets, the task is to calculate the sum of all numbers represented by continuous sequences of digits present in the string S. Examples: Input: S = "11aa32bbb5"Output: 48Explanation: The consecutive sequence of numbers present in the string S are {11, 32, 5}.Therefore, sum = 11 + 32 + 5
5 min read
Practice Tags :
three90RightbarBannerImg