algoadvance

Leetcode 2160. Minimum Sum of Four Digit Number After Splitting Digits

Problem Statement

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.

Clarifying Questions

  1. Input constraints?
    • The input is a four-digit integer in the range [1000, 9999].
  2. How to split the digits of num to form two new numbers?
    • Possible ways to split are taking any two digits for each new number but the sum of digits in the two numbers should be minimized.
  3. Can digits in the number include zeros?
    • Yes, leading zeros are not allowed in the final formed numbers; they should be treated as 0.

Strategy

  1. Extract the four digits from the given integer.
  2. Sort these digits to facilitate minimal combinations.
  3. Construct two numbers from these sorted digits such that their sum is minimized.
  4. Return the sum of these two numbers.

While several methods could solve this problem, sorting the digits simplifies the process as smaller digits combined will yield a smaller sum.

Code

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
    }
}

Explanation

  1. Extracting Digits:
    • We extract each digit by repeatedly taking the modulo 10 of the number and then dividing the number by 10.
  2. Sorting Digits:
    • Sort the digits in ascending order.
  3. Forming Numbers and Calculating Sum:
    • Form two numbers from the sorted digits.
    • number1 is formed using the smallest and the third smallest digit.
    • number2 is formed using the second smallest and the largest digit.
    • This formation ensures minimal possible sum when combining digits.
  4. Return the Sum:
    • Return the sum of number1 and number2.

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI