We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Sum of Four Digit Number After Splitting Digits

Difficulty: Easy


Problem Description

You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2.


Key Insights

  • The problem requires using all digits of a four-digit number to form two new integers.
  • The goal is to minimize the sum of these two integers.
  • Sorting the digits in ascending order allows for optimal pairing to achieve the minimum sum.
  • Pairing the smallest available digits will lead to smaller integer values when combined.

Space and Time Complexity

Time Complexity: O(1) - The operation mainly involves sorting a fixed number of digits (4 digits). Space Complexity: O(1) - Only a constant amount of extra space is used.


Solution

To solve the problem, we will:

  1. Convert the integer num into its constituent digits.
  2. Sort these digits in ascending order.
  3. Form two new integers by pairing the digits optimally: the first integer takes digits from the sorted list at even indices, while the second integer takes digits from the odd indices.
  4. Calculate the sum of these two integers and return the result.

This approach uses sorting, which is efficient given the fixed size of input (4 digits).


Code Solutions

def minimumSum(num: int) -> int:
    # Convert the number into a list of its digits
    digits = [int(d) for d in str(num)]
    # Sort the digits
    digits.sort()
    # Create two new numbers by pairing digits
    new1 = digits[0] * 10 + digits[2]  # First and third digits
    new2 = digits[1] * 10 + digits[3]  # Second and fourth digits
    # Return the sum of the two new numbers
    return new1 + new2
← Back to All Questions