2160. Minimum Sum of Four Digit Number After Splitting Digits
Problem Description
You are given a positive 4-digit integer num
. Your task is to split this number into two new integers new1
and new2
using all four digits from the original number.
The key rules are:
- You must use all four digits from
num
to form the two new numbers - Leading zeros are allowed in the new numbers
- Each digit from
num
must be used exactly once
For example, if num = 2932
:
- The digits available are: 2, 9, 3, 2
- Valid splits include:
[22, 93]
,[23, 92]
,[223, 9]
,[2, 329]
- Invalid would be using only some digits or using a digit more times than it appears
Your goal is to find the split that produces the minimum possible sum of new1 + new2
.
The solution approach sorts the four digits in ascending order. To minimize the sum, the two smallest digits should be placed in the tens position of each number, while the two larger digits go in the ones position. This is why the solution returns 10 * (nums[0] + nums[1]) + nums[2] + nums[3]
, which effectively creates two 2-digit numbers: one with digits nums[0]
and nums[2]
, and another with digits nums[1]
and nums[3]
.
Intuition
To minimize the sum of two numbers formed from four digits, we need to think about place values. A digit in the tens position contributes 10 times its value to the sum, while a digit in the ones position contributes only its face value.
Consider what happens when we form two 2-digit numbers from four digits. The sum would be:
(10 * digit1 + digit2) + (10 * digit3 + digit4)
- This simplifies to:
10 * (digit1 + digit3) + (digit2 + digit4)
From this formula, we can see that the digits placed in the tens positions get multiplied by 10, making them contribute much more to the final sum. Therefore, to minimize the sum, we should place the smallest digits in the tens positions and the larger digits in the ones positions.
Let's trace through an example with num = 2932
:
- Digits sorted:
[2, 2, 3, 9]
- If we place the two smallest (2, 2) in tens positions:
20 + 20 = 40
contribution from tens - Then place the larger ones (3, 9) in ones positions:
3 + 9 = 12
contribution from ones - Total:
40 + 12 = 52
, which gives us numbers23
and29
Compare this with a poor choice like 92 + 23 = 115
. The large digit 9 in the tens position contributes 90
alone, making the sum much larger.
This greedy approach of sorting the digits and assigning the smallest to the tens positions guarantees the minimum possible sum: 10 * (nums[0] + nums[1]) + nums[2] + nums[3]
.
Solution Approach
The implementation follows a straightforward approach to extract digits, sort them, and construct the minimum sum:
Step 1: Extract the digits from the number
nums = [] while num: nums.append(num % 10) num //= 10
- We use the modulo operator
num % 10
to get the last digit - Integer division
num //= 10
removes the last digit - This process continues until
num
becomes 0 - For example, with
num = 2932
: we get digits[2, 3, 9, 2]
(in reverse order)
Step 2: Sort the digits in ascending order
nums.sort()
- After sorting, we have the digits arranged from smallest to largest
- For our example:
[2, 2, 3, 9]
Step 3: Calculate the minimum sum
return 10 * (nums[0] + nums[1]) + nums[2] + nums[3]
nums[0]
andnums[1]
are the two smallest digits - these go in the tens positionsnums[2]
andnums[3]
are the two larger digits - these go in the ones positions- The formula constructs two 2-digit numbers:
- First number:
10 * nums[0] + nums[2]
- Second number:
10 * nums[1] + nums[3]
- Sum:
10 * (nums[0] + nums[1]) + nums[2] + nums[3]
- First number:
Time Complexity: O(1)
- We always process exactly 4 digits and sorting 4 elements is constant time.
Space Complexity: O(1)
- We use a fixed-size array to store 4 digits.
The beauty of this solution lies in its simplicity - by recognizing that minimizing the tens positions is key, we can solve the problem with just sorting and a simple arithmetic formula.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with num = 4325
:
Step 1: Extract digits Starting with 4325, we extract each digit using modulo and integer division:
- 4325 % 10 = 5, then 4325 // 10 = 432
- 432 % 10 = 2, then 432 // 10 = 43
- 43 % 10 = 3, then 43 // 10 = 4
- 4 % 10 = 4, then 4 // 10 = 0 (stop)
We get digits: [5, 2, 3, 4]
Step 2: Sort the digits
After sorting in ascending order: [2, 3, 4, 5]
Step 3: Form the minimum sum To minimize the sum, we place the two smallest digits (2 and 3) in the tens positions:
- First number: 10 × 2 + 4 = 24
- Second number: 10 × 3 + 5 = 35
- Minimum sum: 24 + 35 = 59
Using the formula: 10 × (2 + 3) + 4 + 5 = 10 × 5 + 9 = 59
Why this works: If we had placed larger digits in the tens positions instead (like forming 52 + 43), we'd get a sum of 95, which is much larger. The key insight is that digits in tens positions contribute 10× their value, so we want the smallest digits there.
Solution Implementation
1class Solution:
2 def minimumSum(self, num: int) -> int:
3 # Extract all digits from the 4-digit number into a list
4 digits = []
5 while num > 0:
6 digits.append(num % 10) # Get the last digit
7 num //= 10 # Remove the last digit
8
9 # Sort digits in ascending order to minimize the sum
10 digits.sort()
11
12 # Form two 2-digit numbers to minimize their sum:
13 # Place the two smallest digits in the tens place of each number
14 # Place the two largest digits in the ones place of each number
15 # First number: digits[0] * 10 + digits[2]
16 # Second number: digits[1] * 10 + digits[3]
17 # Total sum: (digits[0] + digits[1]) * 10 + (digits[2] + digits[3])
18 return 10 * (digits[0] + digits[1]) + digits[2] + digits[3]
19
1class Solution {
2 public int minimumSum(int num) {
3 // Array to store the four digits of the input number
4 int[] digits = new int[4];
5
6 // Extract each digit from the number
7 for (int i = 0; num != 0; i++) {
8 digits[i] = num % 10; // Get the last digit
9 num /= 10; // Remove the last digit
10 }
11
12 // Sort the digits in ascending order
13 Arrays.sort(digits);
14
15 // Form two new numbers to minimize the sum:
16 // First number: tens place = smallest digit (digits[0]), ones place = third smallest (digits[2])
17 // Second number: tens place = second smallest (digits[1]), ones place = largest (digits[3])
18 // This gives us: (digits[0] * 10 + digits[2]) + (digits[1] * 10 + digits[3])
19 // Which simplifies to: 10 * (digits[0] + digits[1]) + digits[2] + digits[3]
20 return 10 * (digits[0] + digits[1]) + digits[2] + digits[3];
21 }
22}
23
1class Solution {
2public:
3 int minimumSum(int num) {
4 // Extract all four digits from the number
5 vector<int> digits;
6 while (num > 0) {
7 digits.push_back(num % 10); // Get the last digit
8 num /= 10; // Remove the last digit
9 }
10
11 // Sort digits in ascending order to minimize the sum
12 sort(digits.begin(), digits.end());
13
14 // Form two new numbers by pairing smallest digits as tens place
15 // and larger digits as ones place
16 // new1 = digits[0] * 10 + digits[2]
17 // new2 = digits[1] * 10 + digits[3]
18 // Return their sum
19 return 10 * (digits[0] + digits[1]) + digits[2] + digits[3];
20 }
21};
22
1/**
2 * Finds the minimum sum by splitting a 4-digit number into two 2-digit numbers
3 * @param num - A 4-digit positive integer
4 * @returns The minimum possible sum of two numbers formed from the digits
5 */
6function minimumSum(num: number): number {
7 // Extract all 4 digits from the number into an array
8 const digits: number[] = new Array(4).fill(0);
9
10 // Extract each digit by repeatedly taking modulo 10 and dividing by 10
11 for (let i = 0; i < 4; i++) {
12 digits[i] = num % 10;
13 num = Math.floor(num / 10);
14 }
15
16 // Sort digits in ascending order to minimize the sum
17 // Place smallest digits in tens place for minimum sum
18 digits.sort((a: number, b: number) => a - b);
19
20 // Form two numbers: first number = digits[0]*10 + digits[2]
21 // second number = digits[1]*10 + digits[3]
22 // This can be simplified to: 10*(digits[0] + digits[1]) + digits[2] + digits[3]
23 return 10 * (digits[0] + digits[1]) + digits[2] + digits[3];
24}
25
Time and Space Complexity
Time Complexity: O(1)
The algorithm performs the following operations:
- Extracting 4 digits from the number:
O(4)
=O(1)
since we're always dealing with exactly 4 digits - Sorting 4 elements:
O(4 log 4)
=O(1)
since the array size is constant - Computing the final sum:
O(1)
Since all operations are performed on a fixed-size input (4-digit number), the overall time complexity is O(1)
.
Space Complexity: O(1)
The algorithm uses:
- A list
nums
to store exactly 4 digits:O(4)
=O(1)
- A few variables for intermediate calculations:
O(1)
The space usage is constant regardless of the input value (as long as it's a 4-digit number), so the space complexity is O(1)
.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Assuming Fixed Number Distribution
A common mistake is assuming that we always need to form two 2-digit numbers. While this works for most cases, beginners might not realize why this is optimal and might try to form numbers like a 3-digit and a 1-digit number.
Why it happens: The problem statement allows splits like [223, 9]
or [2, 329]
, which might lead to trying different digit distributions.
The issue: Forming uneven splits (like 3-digit + 1-digit) will always result in a larger sum than forming two 2-digit numbers when trying to minimize the total.
Solution: Understand that for minimum sum, we want the most significant digits to be as small as possible. Having two 2-digit numbers ensures both numbers stay in the same magnitude range.
2. Incorrect Digit Extraction Order
When extracting digits using modulo and division, the digits come out in reverse order (right to left). Some might forget this and assume the array maintains the original digit order.
Example mistake:
# Wrong assumption about digit order digits = [] while num: digits.append(num % 10) num //= 10 # If num = 2932, digits = [2, 3, 9, 2] ❌ Wrong! # Actually, digits = [2, 9, 3, 2] ✓ (extracted right to left)
Solution: The order doesn't matter since we sort the array anyway, but being aware of this prevents confusion during debugging.
3. Overthinking the Pairing Logic
Some might implement complex logic to try different pairings of digits, using nested loops or recursion to find the minimum sum.
Overcomplicated approach:
# Unnecessary complexity
min_sum = float('inf')
for i in range(4):
for j in range(4):
if i != j:
# Try different combinations...
Solution: Recognize that after sorting, the optimal pairing is always fixed: smallest with third-smallest, and second-smallest with largest. This gives us the formula 10 * (digits[0] + digits[1]) + digits[2] + digits[3]
.
4. Handling Leading Zeros Incorrectly
Some might worry about leading zeros and try to avoid them, thinking 02
is not a valid number.
The misconception: Trying to ensure no digit starts with 0, which adds unnecessary complexity.
Solution: The problem explicitly states "leading zeros are allowed," and mathematically, 02
equals 2
. The formula naturally handles this - if digits[0]
or digits[1]
is 0, it simply contributes 0 to the tens place, which is correct.
The three-steps of Depth First Search are:
- Identify states;
- Draw the state-space tree;
- DFS on the state-space tree.
Recommended Readings
Greedy Introduction div class responsive iframe iframe src https www youtube com embed WTslqPbj7I title YouTube video player frameborder 0 allow accelerometer autoplay clipboard write encrypted media gyroscope picture in picture web share allowfullscreen iframe div When do we use greedy Greedy algorithms tend to solve optimization problems Typically they will ask you to calculate the max min of some value Commonly you may see this phrased in the problem as max min longest shortest largest smallest etc These keywords can be identified by just scanning
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Sorting Summary Comparisons We presented quite a few sorting algorithms and it is essential to know the advantages and disadvantages of each one The basic algorithms are easy to visualize and easy to learn for beginner programmers because of their simplicity As such they will suffice if you don't know any advanced
Want a Structured Path to Master System Design Too? Don’t Miss This!