Problem Description
Given a positive integer num consisting of exactly four digits, split num into two new integers new1 and new2 using all the digits found in num. Leading zeros are allowed in new1 and new2. The objective is to minimize the sum of new1 and new2.
Key Insights
- Sort the four digits in ascending order.
- Distribute the sorted digits alternately between the two numbers.
- This approach minimizes the weight (place value) of the larger digits when forming both numbers.
- Greedy strategy ensures the minimal possible sum by balancing the numbers.
Space and Time Complexity
Time Complexity: O(n log n) where n is the number of digits (n=4, so effectively constant time) Space Complexity: O(n)
Solution
Extract the digits from the input number and sort them in non-decreasing order. Build two numbers by concatenating digits: assign the first and third smallest digits to form the first number, and the second and fourth smallest digits for the second number. This alternating distribution minimizes the overall sum by placing smaller digits in higher significance positions in both numbers.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java.