Problem Description
Given a positive integer num, split it into two non-negative integers num1 and num2 such that the concatenation of all digits in num1 and num2 is a permutation of the digits in num. The goal is to minimize the sum num1 + num2. Note that both numbers can have leading zeros.
Key Insights
- Sorting the digits in ascending order helps to balance the values of num1 and num2.
- By alternately assigning digits from the sorted list to the two numbers, we distribute the weight of the higher digits evenly.
- Building the numbers by combining digits from the sorted list ensures that neither number is overly large, minimizing their sum.
- Converting the final strings to integers will automatically handle any leading zeros.
Space and Time Complexity
Time Complexity: O(d log d), where d is the number of digits in num. Since num is at most 10^9, d is at most 10, making this effectively constant time. Space Complexity: O(d), for storing the sorted digits and the constructed strings for num1 and num2.
Solution
The algorithm proceeds by first converting the integer num into an array of its digits and then sorting this array in ascending order. Two numbers, num1 and num2, are built by iterating through the sorted list and alternately appending digits to each number. This alternating assignment minimizes the sum since smaller digits are distributed evenly between the two numbers. Finally, the two constructed numbers (which might include leading zeros) are converted back to integers and summed to produce the final answer.