Split With Minimum Sum - 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.
  • num1 and num2 can contain leading zeros.

Return the minimum possible sum of num1 and num2.

Input & Output

Example 1 — Basic Case
$ Input: num = 4325
Output: 59
💡 Note: Split digits [4,3,2,5] → sort to [2,3,4,5] → alternate assignment: num1=24, num2=35 → sum = 24 + 35 = 59
Example 2 — Two Digits
$ Input: num = 687
Output: 75
💡 Note: Split digits [6,8,7] → sort to [6,7,8] → alternate: num1=68, num2=7 → sum = 68 + 7 = 75
Example 3 — With Zeros
$ Input: num = 1000
Output: 10
💡 Note: Split digits [1,0,0,0] → already sorted → alternate: num1=10, num2=00 → sum = 10 + 0 = 10

Constraints

  • 10 ≤ num ≤ 109
  • num does not contain leading zeros

Visualization

Tap to expand
Split With Minimum Sum INPUT num = 4325 4 3 2 5 Extract digits: [4, 3, 2, 5] Goal: Split into num1 and num2 Minimize: num1 + num2 Use all digits exactly once Leading zeros allowed ALGORITHM STEPS 1 Sort Digits [4,3,2,5] --> [2,3,4,5] 2 3 4 5 2 Alternate Distribution Give smallest to num1, next to num2 3 Build Numbers Alternate: idx 0,2 and idx 1,3 num1 2 4 num2 3 5 4 Calculate Sum num1=24, num2=35 24 + 35 = 59 FINAL RESULT Optimal Split Found: num1 24 + num2 35 Minimum Sum 59 Verification: Digits used: 2,4 + 3,5 = {2,3,4,5} = {4,3,2,5} OK - Valid permutation! Key Insight: To minimize sum, place smallest digits in highest place values. By sorting and alternating, we ensure both numbers stay small and balanced. Greedy approach works because smaller digits in tens/hundreds places contribute less to the total sum than larger digits would. TutorialsPoint - Split With Minimum Sum | Greedy - Sort and Alternate
Asked in
Amazon 15 Microsoft 12
12.5K Views
Medium Frequency
~15 min Avg. Time
340 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