Sum of Numbers With Units Digit K

Problem Description

So, you’ve stumbled upon the LeetCode problem titled “Sum of Numbers With Units Digit K.” Imagine you’re at a party, and everyone is trying to figure out how to split the bill. But there’s a catch! The total amount must end with a specific digit, K. Sounds fun, right? Well, it’s not as easy as it sounds. You need to find the minimum number of times you can add a number that ends with K to get to your desired total, num.

For example, if K is 3 and you want to reach 9, you can simply add 3 three times (3 + 3 + 3 = 9). But if you want to reach 10, you’re out of luck because no combination of numbers ending in 3 will get you there.

Code Solution


class Solution:
    def minimumNumbers(self, num: int, k: int) -> int:
        if num == 0:
            return 0

        for i in range(1, 11):
            if i * k > num + 1:
                break
            if i * k % 10 == num % 10:
                return i

        return -1

Approach Explanation

The code works by iterating through potential counts of numbers (from 1 to 10) that could sum up to the desired number, num. For each count, it checks if the sum of those numbers, which all end with K, can match the last digit of num. If it finds a match, it returns the count. If it doesn’t find any valid combinations, it returns -1.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(1) – The loop runs a fixed number of times (at most 10).
Space Complexity O(1) – No additional space is used that scales with input size.

Real-World Example

Let’s say you’re at a bakery, and you want to buy cupcakes that cost $k each. You have a specific amount of money, num, and you want to know how many cupcakes you can buy without going over your budget, while ensuring the total cost ends with a specific digit. This problem is just like that!

Similar Problems