Minimum Sum of Four Digit Number After Splitting Digits - Problem

You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.

For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].

Return the minimum possible sum of new1 and new2.

Input & Output

Example 1 — Basic Case
$ Input: num = 2932
Output: 52
💡 Note: We can split digits [2,9,3,2]. After sorting: [2,2,3,9]. Optimal split: 23 + 29 = 52
Example 2 — With Leading Zero
$ Input: num = 4009
Output: 13
💡 Note: Digits are [4,0,0,9]. After sorting: [0,0,4,9]. Optimal split: 04 + 09 = 4 + 9 = 13
Example 3 — All Same Digits
$ Input: num = 1111
Output: 22
💡 Note: All digits are 1. Any split gives the same result: 11 + 11 = 22

Constraints

  • 1000 ≤ num ≤ 9999

Visualization

Tap to expand
Minimum Sum After Splitting Digits INPUT 4-Digit Number: 2932 Extract Digits: 2 9 3 2 Sorted (Ascending): 2 2 3 9 [0] [1] [2] [3] [2, 2, 3, 9] ALGORITHM STEPS 1 Sort Digits Arrange ascending order 2 Distribute Optimally Small digits at tens place 3 Form Two Numbers new1 and new2 4 Calculate Sum Add new1 + new2 Greedy Distribution: new1: 2 3 = 23 new2: 2 9 = 29 d[0],d[2] and d[1],d[3] FINAL RESULT Optimal Split: new1 23 + new2 29 = Minimum Sum 52 Verification: 23 = 2*10 + 3 = 23 29 = 2*10 + 9 = 29 23 + 29 = 52 OK Key Insight: To minimize the sum, place the two smallest digits in the tens places of new1 and new2. The remaining two digits go in the units places. Formula: (d[0]+d[1])*10 + d[2] + d[3] For [2,2,3,9]: (2+2)*10 + 3 + 9 = 40 + 12 = 52. This greedy approach always yields minimum sum. TutorialsPoint - Minimum Sum of Four Digit Number After Splitting Digits | Greedy Optimal Distribution
Asked in
Google 15 Amazon 12 Microsoft 8
44.9K Views
Medium Frequency
~8 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen