#2578
Split With Minimum Sum
EasyMathGreedySortingSortingGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages sorting the digits and then distributing them alternately between two numbers. This ensures that the smaller digits contribute to the overall sum in a balanced manner, minimizing the final sum.
⚙️
Algorithm
4 steps- 1Step 1: Convert the number into a list of its digits.
- 2Step 2: Sort the digits in non-decreasing order.
- 3Step 3: Distribute the digits between num1 and num2 alternately.
- 4Step 4: Convert num1 and num2 back to integers and return their sum.
solution.py12 lines
1# Full working Python code
2
3def min_sum_split(num):
4 digits = sorted(str(num))
5 num1, num2 = '', ''
6 for i in range(len(digits)):
7 if i % 2 == 0:
8 num1 += digits[i]
9 else:
10 num2 += digits[i]
11 return int(num1) + int(num2)
12ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, and the space complexity is O(n) because we store the digits in a list.
- 1Sorting the digits helps in minimizing the sum.
- 2Distributing digits alternately balances the contribution to both numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.