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

Split With Minimum Sum

Number: 2650

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

Given a positive integer num, split it into two non-negative integers num1 and num2 such that the concatenation of all digits in num1 and num2 is a permutation of the digits in num. The goal is to minimize the sum num1 + num2. Note that both numbers can have leading zeros.


Key Insights

  • Sorting the digits in ascending order helps to balance the values of num1 and num2.
  • By alternately assigning digits from the sorted list to the two numbers, we distribute the weight of the higher digits evenly.
  • Building the numbers by combining digits from the sorted list ensures that neither number is overly large, minimizing their sum.
  • Converting the final strings to integers will automatically handle any leading zeros.

Space and Time Complexity

Time Complexity: O(d log d), where d is the number of digits in num. Since num is at most 10^9, d is at most 10, making this effectively constant time. Space Complexity: O(d), for storing the sorted digits and the constructed strings for num1 and num2.


Solution

The algorithm proceeds by first converting the integer num into an array of its digits and then sorting this array in ascending order. Two numbers, num1 and num2, are built by iterating through the sorted list and alternately appending digits to each number. This alternating assignment minimizes the sum since smaller digits are distributed evenly between the two numbers. Finally, the two constructed numbers (which might include leading zeros) are converted back to integers and summed to produce the final answer.


Code Solutions

# Python solution for Split With Minimum Sum
def splitNum(num):
    # Convert the number to a string and then create a sorted list of its digits
    digits = sorted(str(num))
    
    # Initialize two string holders for num1 and num2
    num1_digits, num2_digits = [], []
    
    # Distribute the digits alternately
    for i, digit in enumerate(digits):
        if i % 2 == 0:
            num1_digits.append(digit)  # Append to num1 on even indices
        else:
            num2_digits.append(digit)  # Append to num2 on odd indices
            
    # Convert the lists of digits back into integers (converting strings to int handles leading zeros)
    num1 = int("".join(num1_digits))
    num2 = int("".join(num2_digits))
    
    # Return the sum of the two numbers
    return num1 + num2

# Example usage:
print(splitNum(4325))  # Output should be 59
← Back to All Questions