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

Number: 2264

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

Given a positive integer num consisting of exactly four digits, split num into two new integers new1 and new2 using all the digits found in num. Leading zeros are allowed in new1 and new2. The objective is to minimize the sum of new1 and new2.


Key Insights

  • Sort the four digits in ascending order.
  • Distribute the sorted digits alternately between the two numbers.
  • This approach minimizes the weight (place value) of the larger digits when forming both numbers.
  • Greedy strategy ensures the minimal possible sum by balancing the numbers.

Space and Time Complexity

Time Complexity: O(n log n) where n is the number of digits (n=4, so effectively constant time) Space Complexity: O(n)


Solution

Extract the digits from the input number and sort them in non-decreasing order. Build two numbers by concatenating digits: assign the first and third smallest digits to form the first number, and the second and fourth smallest digits for the second number. This alternating distribution minimizes the overall sum by placing smaller digits in higher significance positions in both numbers.


Code Solutions

Below are implementations in Python, JavaScript, C++, and Java.

# Function to compute minimum sum after splitting digits
def minimumSum(num):
    # Convert the number to a list of digit strings
    digits = list(str(num))
    # Sort the digits in ascending order
    digits.sort()
    
    # Form two numbers by distributing digits alternately
    new1 = int(digits[0] + digits[2])
    new2 = int(digits[1] + digits[3])
    
    # Return the sum of the two numbers
    return new1 + new2

# Example usage
print(minimumSum(2932))  # Output: 52
← Back to All Questions