Minimum sum of two numbers formed from digits of an array in O(n)

• Difficulty Level : Medium
• Last Updated : 12 May, 2021

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 = 604
Input: arr[] = {5, 3, 0, 7, 4}
Output: 82

Approach: A minimum number will be formed from the set of digits when smallest digit appears at the most significant position and next to smallest digit appears at next most significant position and so on…
The idea is to build two numbers by alternating picking digits from the array (assuming it is sorted in ascending). So the first number is formed by digits present in odd positions in the array and the second number is formed by digits from even positions in the array. Finally, we return the sum of the first and second number. In order to reduce the time complexity, the array can be sorted in O(n) using the frequency array of digits as every element of the original array is a single digit i.e. there can be at most 10 distinct elements.
Below is the implementation of the above approach:

C++

 // C++ implementation of above approach#includeusing namespace std; // Function to return the required minimum sumint minSum(vector arr, int n){     // Array to store the    // frequency of each digit    int MAX = 10;    int *freq = new int[MAX];    for (int i = 0; i < n; i++) {         // Store count of every digit        freq[arr[i]]++;    }     // Update arr[] such that it is    // sorted in ascending    int k = 0;    for (int i = 0; i < MAX; i++) {         // Adding elements in arr[]        // in sorted order        for (int j = 0; j < freq[i]; j++) {            arr[k++] = i;        }    }     int num1 = 0;    int num2 = 0;     // Generating numbers alternatively    for (int i = 0; i < n; i++) {         if (i % 2 == 0)            num1 = num1 * MAX + arr[i];        else            num2 = num2 * MAX + arr[i];    }     // Return the minimum possible sum    return num1 + num2;} // Driver codeint main(void){    vectorarr = { 6, 8, 4, 5, 2, 3 };    int n = arr.size();    cout << minSum(arr, n);}// This code is contributed by ankush_953

Java

 // Java implementation of above approachpublic class GFG {     public static final int MAX = 10;     // Function to return the required minimum sum    static int minSum(int arr[], int n)    {         // Array to store the        // frequency of each digit        int freq[] = new int[MAX];        for (int i = 0; i < n; i++) {             // Store count of every digit            freq[arr[i]]++;        }         // Update arr[] such that it is        // sorted in ascending        int k = 0;        for (int i = 0; i < MAX; i++) {             // Adding elements in arr[]            // in sorted order            for (int j = 0; j < freq[i]; j++) {                arr[k++] = i;            }        }         int num1 = 0;        int num2 = 0;         // Generating numbers alternatively        for (int i = 0; i < n; i++) {             if (i % 2 == 0)                num1 = num1 * MAX + arr[i];            else                num2 = num2 * MAX + arr[i];        }         // Return the minimum possible sum        return num1 + num2;    }     // Driver code    public static void main(String[] args)    {        int arr[] = { 6, 8, 4, 5, 2, 3 };        int n = arr.length;        System.out.print(minSum(arr, n));    }}

Python3

 # Python implementation of above approach# Function to return the required minimum sumdef minSum(arr, n):    # Array to store the    # frequency of each digit    MAX = 10    freq = *MAX         for i in range(n):        # Store count of every digit        freq[arr[i]] += 1     # Update arr[] such that it is    # sorted in ascending    k = 0    for i in range(MAX):        # Adding elements in arr[]        # in sorted order        for j in range(0,freq[i]):            arr[k] = i            k += 1     num1 = 0    num2 = 0     # Generating numbers alternatively    for i in range(n):        if i % 2 == 0:            num1 = num1 * MAX + arr[i]        else:            num2 = num2 * MAX + arr[i]     # Return the minimum possible sum    return num1 + num2  # Driver codearr = [ 6, 8, 4, 5, 2, 3 ]n = len(arr);print(minSum(arr, n)) #This code is contributed by ankush_953

C#

 // C# implementation of above approachusing System; class GFG {     public static int MAX = 10;    // Function to return the required minimum sum    static int minSum(int[] arr, int n)    {         // Array to store the        // frequency of each digit        int[] freq = new int[MAX];        for (int i = 0; i < n; i++) {             // Store count of every digit            freq[arr[i]]++;        }         // Update arr[] such that it is        // sorted in ascending        int k = 0;        for (int i = 0; i < MAX; i++) {             // Adding elements in arr[]            // in sorted order            for (int j = 0; j < freq[i]; j++) {                arr[k++] = i;            }        }         int num1 = 0;        int num2 = 0;         // Generating numbers alternatively        for (int i = 0; i < n; i++) {             if (i % 2 == 0)                num1 = num1 * MAX + arr[i];            else                num2 = num2 * MAX + arr[i];        }         // Return the minimum possible sum        return num1 + num2;    }     // Driver code    static public void Main()    {        int[] arr = { 6, 8, 4, 5, 2, 3 };        int n = arr.Length;        Console.WriteLine(minSum(arr, n));    }} // This code is contributed by jit_t.

Javascript


Output:
604

Time Complexity: O(n)

My Personal Notes arrow_drop_up