23. Minimum Sum
โ GFG solution to the Minimum Sum problem: form two numbers using all digits to minimize their sum using greedy approach and counting sort. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given an array arr[] consisting of digits, your task is to form two numbers using all the digits such that their sum is minimized. Return the minimum possible sum as a string with no leading zeroes.
The key insight is to distribute the smallest digits optimally between two numbers to minimize their sum.
๐ Examples
Example 1
Input: arr[] = [6, 8, 4, 5, 2, 3]
Output: "604"
Explanation: The minimum sum is formed by numbers 358 and 246.
358 + 246 = 604Example 2
Input: arr[] = [5, 3, 0, 7, 4]
Output: "82"
Explanation: The minimum sum is formed by numbers 35 and 047.
35 + 47 = 82 (leading zero removed from 047)Example 3
๐ Constraints
$2 \le \text{arr.size()} \le 10^6$
$0 \le \text{arr}[i] \le 9$
โ
My Approach
The optimal approach uses Counting Sort followed by Greedy Distribution to minimize the sum:
Counting + Greedy Distribution
Count Digit Frequencies:
Use a counting array to store frequency of each digit (0-9).
This naturally sorts the digits in O(n) time.
Greedy Distribution Strategy:
Distribute digits alternately between two strings
s1ands2.Start with the smallest available digit to ensure minimum sum.
Skip leading zeros to avoid invalid number formation.
String Addition:
Implement custom string addition to handle large numbers.
Add digits from right to left with carry propagation.
Remove trailing zeros from the result.
Optimization Details:
Use alternating distribution to balance the lengths of both numbers.
Smaller digits in higher positions contribute less to the final sum.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the array size. Counting takes O(n), distribution takes O(n), and string addition takes O(n) where n is the maximum length of formed numbers.
Expected Auxiliary Space Complexity: O(1), as we only use constant extra space for counting array (size 10) and string operations (excluding the output strings).
๐งโ๐ป Code (C++)
๐งโ๐ป Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated