Leetcode 2160. Minimum Sum of Four Digit Number After Splitting Digits
You are given a positive integer num
consisting of exactly four digits. The task is to split the given number into two new numbers by using the digits of the original number. The goal is to minimize the sum of these two new numbers.
Return the minimum possible sum of the two new numbers.
[1000, 9999]
.num
to form two new numbers?
While several methods could solve this problem, sorting the digits simplifies the process as smaller digits combined will yield a smaller sum.
import java.util.Arrays;
public class MinimumSum {
public int minimumSum(int num) {
// Extracting digits from the given number
int[] digits = new int[4];
for (int i = 0; i < 4; i++) {
digits[i] = num % 10;
num /= 10;
}
// Sorting the digits
Arrays.sort(digits);
// Constructing the minimum sum from the sorted digits
// Form two numbers: (digits[0] and digits[2]) and (digits[1] and digits[3])
int number1 = digits[0] * 10 + digits[2];
int number2 = digits[1] * 10 + digits[3];
// Return the sum of these two numbers
return number1 + number2;
}
public static void main(String[] args) {
MinimumSum solution = new MinimumSum();
// Example Test Case
System.out.println(solution.minimumSum(2932)); // Expected output: 52
}
}
number1
is formed using the smallest and the third smallest digit.number2
is formed using the second smallest and the largest digit.number1
and number2
.Time Complexity: (O(1)) - Since the number of digits (4) is constant, operations such as digit extraction and sorting (with a fixed size of 4) take constant time.
Space Complexity: (O(1)) - Space required does not grow with input size, constant space is used for storing a few integers and a fixed-size array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?