Split With Minimum Sum - Problem

Imagine you have a positive integer and need to strategically split its digits into two separate numbers to achieve the minimum possible sum.

Given a positive integer num, your task is to split it into two non-negative integers num1 and num2 such that:

  • The concatenation of num1 and num2 uses exactly the same digits as the original num (a permutation)
  • Each digit from num appears in either num1 or num2, but the total count of each digit remains the same
  • Leading zeros are allowed in both num1 and num2

Your goal is to find the arrangement that produces the minimum possible sum of num1 + num2.

Example: For num = 4325, you could split it as 24 + 35 = 59, but a better split would be 23 + 45 = 68. Can you find an even better arrangement?

Input & Output

example_1.py โ€” Basic Split
$ Input: num = 4325
โ€บ Output: 59
๐Ÿ’ก Note: Split digits [4,3,2,5] โ†’ sort to [2,3,4,5] โ†’ alternate assignment gives num1=24, num2=35, sum=59
example_2.py โ€” Two Digits
$ Input: num = 687
โ€บ Output: 75
๐Ÿ’ก Note: Sort [6,8,7] to [6,7,8] โ†’ num1=68, num2=7 โ†’ sum=75. Alternative split 6|78=84 is larger.
example_3.py โ€” Edge Case
$ Input: num = 10
โ€บ Output: 1
๐Ÿ’ก Note: Sort [1,0] โ†’ num1=1, num2=0 โ†’ sum=1. The 0 forms a valid number by itself.

Visualization

Tap to expand
Optimal Card Distribution StrategyStep 1-2: Sort Cards by ValueOriginal4325SORTSorted2345Step 3-4: Alternate DistributionHand 1 (Even positions)24Number: 24Hand 2 (Odd positions)35Number: 35Final Result24 + 35 = 59(Minimum possible sum)
Understanding the Visualization
1
Lay Out Cards
Place all digit cards on the table: 4, 3, 2, 5
2
Sort by Value
Arrange cards from smallest to largest: 2, 3, 4, 5
3
Alternate Distribution
Deal alternately to two hands: Hand 1 gets 2,4 and Hand 2 gets 3,5
4
Form Numbers
Read each hand left-to-right: Hand 1 = 24, Hand 2 = 35
5
Calculate Total
Sum the values: 24 + 35 = 59 (minimum possible)
Key Takeaway
๐ŸŽฏ Key Insight: The greedy approach works because placing smaller digits in higher-value positions (leftmost) has the maximum impact on minimizing the sum. Alternating assignment keeps the two numbers roughly equal in length, preventing one number from dominating the sum.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

Sorting the digits takes O(n log n) time, where n is the number of digits

n
2n
โšก Linearithmic
Space Complexity
O(n)

Space to store the sorted digits and form the two numbers

n
2n
โšก Linearithmic Space

Constraints

  • 10 โ‰ค num โ‰ค 109
  • num does not contain leading zeros
  • The number has at least 2 digits
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
21.1K Views
Medium Frequency
~12 min Avg. Time
842 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