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 k as 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
Digital Pattern MatchingExample: num = 58, k = 9Target units digit: 8Testing pattern: count ร— k mod 101 ร— 9= 9Units: 92 ร— 9= 18Units: 8 โœ“3 ร— 9= 27Units: 74 ร— 9= 36Units: 6...โœ“ Found match at count = 2Verification: 2 ร— 9 = 18 โ‰ค 58 โœ“Answer: 2 (e.g., use numbers [9, 49])
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค num โ‰ค 3000
  • 0 โ‰ค k โ‰ค 9
  • All integers in the set must be positive
  • The set can contain duplicate values
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
28.8K Views
Medium Frequency
~18 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen