1732. Split Into Two Numbers
A puzzle magazine gives you a string num of digits. Use every digit exactly once to write two non-negative integers, in any order of digits you like. Leading zeros are allowed in the two numbers, so a number such as 007 is simply 7, and a number may even be made only of zeros.
Return the smallest possible sum of the two integers as a long. Sort the digits ascending and deal them out alternately, one to each number, so that the smaller digits sit in the more significant places of both numbers. This runs in O(L log L) time and O(L) space, where L is the length of num.
Example 1
- Input:
- num = "4325"
- Output:
- 59
- Explanation:
Digits sorted are 2, 3, 4, 5; dealing them alternately builds 24 and 35, whose sum is 59.
Example 2
- Input:
- num = "10"
- Output:
- 1
- Explanation:
The digits 0 and 1 become the numbers 0 and 1, with sum 1.
Example 3
- Input:
- num = "1000"
- Output:
- 1
- Explanation:
The numbers 0 (from 0, 0) and 1 (from 0, 1) have sum 1.
Constraints
2 ≤ num.length ≤ 15
num consists of digits only and has no leading zero
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(L log L)
- Space
- O(L)