Sum of Numbers With Units Digit K - Problem
You're tasked with finding the minimum number of positive integers that satisfy two specific conditions:
- Each integer must have
kas its units digit (the rightmost digit) - The sum of all these integers equals
num
For example, if num = 58 and k = 9, you need positive integers ending in 9 that sum to 58. You could use [9, 49] (size 2) or [9, 9, 9, 9, 22] (size 5), but the minimum size would be 2.
Goal: Return the minimum possible size of such a set, or -1 if it's impossible to create such a set.
Note: The set can contain duplicate numbers, and an empty set has sum 0.
Input & Output
example_1.py โ Basic Case
$
Input:
num = 58, k = 9
โบ
Output:
2
๐ก Note:
We need positive integers ending in 9 that sum to 58. The optimal solution uses 2 numbers: [9, 49]. Both end in 9 and sum to 58.
example_2.py โ Impossible Case
$
Input:
num = 37, k = 2
โบ
Output:
-1
๐ก Note:
We need numbers ending in 2 to sum to 37. But any sum of numbers ending in 2 will have an even units digit (2, 4, 6, 8, 0), never 7. Therefore impossible.
example_3.py โ Edge Case Zero
$
Input:
num = 0, k = 7
โบ
Output:
0
๐ก Note:
To get sum 0, we use an empty set (0 numbers). This is valid since the problem states an empty set sums to 0.
Visualization
Tap to expand
Understanding the Visualization
1
Identify the target
Extract the units digit of our target sum
2
Find the pattern
Calculate how many coins we need to match the target's ending digit
3
Verify feasibility
Check if our minimum sum doesn't exceed the target
4
Return the answer
The first valid pattern gives us the minimum count
Key Takeaway
๐ฏ Key Insight: Units digits of multiples follow predictable patterns that repeat every 10 steps, allowing us to find the answer in constant time rather than trying all possibilities.
Time & Space Complexity
Time Complexity
O(1)
We only check at most 10 possible values since units digits repeat every 10
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space
โ Linear Space
Constraints
- 0 โค num โค 3000
- 0 โค k โค 9
- All integers in the set must be positive
- The set can contain duplicate values
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code