Split With Minimum Sum — LeetCode 2578 Python Solution
- Problem
- #2578
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given a positive integer num, split it into two non-negative integers num1 and num2 such that: The concatenation of num1 and num2 is a permutation of num. In other words, the sum of the number of occurrences of each digit in num1 and num2 is equal to the number of occurrences of that digit in num.
Example
- Input
- num = 4325
- Output
- 59
- Explanation
- We can split 4325 so that num1 is 24 and num2 is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
Python solution
class Solution:
def splitNum(self, num: int) -> int:
cnt = Counter()
n = 0
while num:
cnt[num % 10] += 1
num //= 10
n += 1
ans = [0] * 2
j = 0
for i in range(n):
while cnt[j] == 0:
j += 1
cnt[j] -= 1
ans[i & 1] = ans[i & 1] * 10 + j
return sum(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2578. Split With Minimum Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2578. Split With Minimum Sum?
- LeetCode 2578. Split With Minimum Sum is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2578. Split With Minimum Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2578. Split With Minimum Sum?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 2578. Split With Minimum Sum cover?
- LeetCode 2578. Split With Minimum Sum is tagged Greedy, Math and Sorting on LeetCode.