Sum of Numbers With Units Digit K Problem
#2310
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2310.
Given two integers num and k, consider a set of positive integers with the following properties:
- The units digit of each integer is
k. - The sum of the integers is
num.
Return the minimum possible size of such a set, or -1 if no such set exists.
Note:
- The set can contain multiple instances of the same integer, and the sum of an empty set is considered
0. - The units digit of a number is the rightmost digit of the number.
Example 1:
Input: num = 58, k = 9
Output: 2
Explanation:
One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.
Another valid set is [19,39].
It can be shown that 2 is the minimum possible size of a valid set.
Example 2:
Input: num = 37, k = 2
Output: -1
Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.
Example 3:
Input: num = 0, k = 7
Output: 0
Explanation: The sum of an empty set is considered 0.
Constraints:
0 <= num <= 30000 <= k <= 9
Solution
Approach: Math + Enumeration
Every number in the set has the form 10a + k, so if the set has i numbers, then num - i * k must be a non-negative multiple of 10. Only the units digit matters: the tens and higher digits can be anything. Try i from 1 to 10 (the units digit of i * k repeats after that) and return the first i with i * k <= num and i * k having the same units digit as num. If num is 0 the answer is 0, and if no i works the answer is -1.
Complexity: Time O(1) (at most 10 tries), space O(1).
class Solution:
def minimumNumbers(self, num: int, k: int) -> int:
if num == 0:
return 0
for i in range(1, num + 1):
if (t := num - k * i) >= 0 and t % 10 == 0:
return i
return -1