Minimum sum of two numbers formed from digits of an array

Pattern: Top K

medium

Use every digit in one of two numbers. Smaller digits should sit in the higher places, and the two numbers should be as short as possible, so take digits from smallest to largest and deal them to the two numbers in turn. Add them as strings, since they may be long.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given an array of digits (0 to 9), use every digit exactly once to form two numbers, and return their smallest possible sum as a string without leading zeros. [6, 8, 4, 5, 2, 3] gives "604"; [5, 3, 0, 7, 4] gives "82" (047 + 35).

The catalogue has no practice link for this one.

Think first

  • Which digits should go in the highest places?
  • How long should each number be?
  • Why might a normal integer type fail?

Hints

    Brute force, and why it fails

    Try every way to split the digits between the two numbers, sorting each part: O(2ⁿ × n).

    The key insight

    Dealing the sorted digits alternately puts the smallest digits in the highest places of both numbers at once. A min heap, or a sort, gives them in order.

    Dry run

    digits2 3 4 5 6 8

    arr = [6, 8, 4, 5, 2, 3]. Sorted digits: 2, 3, 4, 5, 6, 8.

    Step 1 of 3

    The plan

    heap = min heap of the digits
    while heap: a.append(pop); if heap: b.append(pop)
    return add(a, b) as decimal strings, leading zeros removed
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Sorting the digits dominates; the addition is O(n).

    Edge cases

    • All zeros: "0".
    • One digit: that digit.
    • Leading zeros in the numbers do not change their values.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public String minSum(int[] arr) {
            PriorityQueue<Integer> heap = new PriorityQueue<>();   // smallest digit first
            for (int d : arr) heap.add(d);
            List<Integer> a = new ArrayList<>(), b = new ArrayList<>();
            while (!heap.isEmpty()) {
                a.add(heap.poll());                 // deal the digits alternately, smallest first
                if (!heap.isEmpty()) b.add(heap.poll());
            }
            return add(a, b);
        }
    
        private String add(List<Integer> a, List<Integer> b) {   // add two digit lists as decimal numbers
            StringBuilder out = new StringBuilder();
            int i = a.size() - 1, j = b.size() - 1, carry = 0;
            while (i >= 0 || j >= 0 || carry > 0) {
                int s = carry + (i >= 0 ? a.get(i) : 0) + (j >= 0 ? b.get(j) : 0);
                out.append(s % 10);
                carry = s / 10;
                i--;
                j--;
            }
            while (out.length() > 1 && out.charAt(out.length() - 1) == '0') out.setLength(out.length() - 1);   // leading zeros
            return out.reverse().toString();
        }
    }

    C++

    class Solution {
    public:
        string minSum(vector<int>& arr) {
            priority_queue<int, vector<int>, greater<int>> heap(arr.begin(), arr.end());   // smallest digit first
            vector<int> a, b;
            while (!heap.empty()) {
                a.push_back(heap.top()); heap.pop();    // deal the digits alternately, smallest first
                if (!heap.empty()) { b.push_back(heap.top()); heap.pop(); }
            }
            return add(a, b);
        }
    
        string add(const vector<int>& a, const vector<int>& b) {   // add two digit lists as decimal numbers
            string out;
            int i = static_cast<int>(a.size()) - 1, j = static_cast<int>(b.size()) - 1, carry = 0;
            while (i >= 0 || j >= 0 || carry > 0) {
                int s = carry + (i >= 0 ? a[i] : 0) + (j >= 0 ? b[j] : 0);
                out += static_cast<char>('0' + s % 10);
                carry = s / 10;
                i--;
                j--;
            }
            while (out.size() > 1 && out.back() == '0') out.pop_back();   // leading zeros
            reverse(out.begin(), out.end());
            return out;
        }
    };

    Python

    import heapq
    
    class Solution:
        def minSum(self, arr: list[int]) -> str:
            heap = list(arr)
            heapq.heapify(heap)                     # smallest digit first
            a, b = [], []
            while heap:
                a.append(heapq.heappop(heap))       # deal the digits alternately, smallest first
                if heap:
                    b.append(heapq.heappop(heap))
            return self.add(a, b)
    
        def add(self, a: list[int], b: list[int]) -> str:   # add two digit lists as decimal numbers
            out, carry = [], 0
            i, j = len(a) - 1, len(b) - 1
            while i >= 0 or j >= 0 or carry:
                s = carry + (a[i] if i >= 0 else 0) + (b[j] if j >= 0 else 0)
                out.append(str(s % 10))
                carry = s // 10
                i, j = i - 1, j - 1
            text = "".join(reversed(out)).lstrip("0")
            return text or "0"

    Common mistakes

    • Putting all small digits into one number.
    • Adding with 64-bit integers and overflowing.
    • Leaving leading zeros in the answer.

    Similar problems