#2160
Minimum Sum of Four Digit Number After Splitting Digits
EasyMathGreedySortingSortingGreedy Algorithms
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)
By sorting the digits and strategically pairing the smallest digits, we can construct the two smallest two-digit numbers efficiently. This minimizes the sum without needing to check every combination.
⚙️
Algorithm
4 steps- 1Step 1: Extract the digits from the number and store them in an array.
- 2Step 2: Sort the array of digits.
- 3Step 3: Form two two-digit numbers using the smallest digits: new1 from the first and third smallest, new2 from the second and fourth smallest.
- 4Step 4: Return the sum of new1 and new2.
solution.py3 lines
1def minimumSum(num):
2 digits = sorted([int(d) for d in str(num)])
3 return (digits[0] * 10 + digits[2]) + (digits[1] * 10 + digits[3])ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the digits. This is efficient given the fixed size of n (4).
- 1Sorting the digits allows for optimal pairing to minimize the sum.
- 2Using the two smallest digits in the tens place of the two numbers minimizes their overall contribution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.