Minimum Sum of Four Digit Number After Splitting Digits — LeetCode 2160 Python Solution

EasyGreedyMathSorting
Problem
#2160
Pattern
Greedy
Reading time
2 min

The problem

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.

Example

Input
num = 2932
Output
52
Explanation
Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.

Python solution

Python
class Solution:
    def minimumSum(self, num: int) -> int:
        nums = []
        while num:
            nums.append(num % 10)
            num //= 10
        nums.sort()
        return 10 * (nums[0] + nums[1]) + nums[2] + nums[3]

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits?
LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits is rated Easy on LeetCode.
What topics does LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits cover?
LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits is tagged Greedy, Math and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview