Sum of Numbers With Units Digit K - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: num = 58, k = 9
Output: 2
💡 Note: We can use two numbers: 19 and 39. Both end in 9 and 19 + 39 = 58. This is the minimum possible size.
Example 2 — Single Number
$ Input: num = 37, k = 2
Output: -1
💡 Note: No combination of positive numbers ending in 2 can sum to 37 (which ends in 7). Numbers ending in 2 create sums ending in even digits only.
Example 3 — Zero Sum
$ Input: num = 0, k = 7
Output: 0
💡 Note: Empty set has sum 0, so we need 0 numbers.

Constraints

  • 0 ≤ num ≤ 3000
  • 0 ≤ k ≤ 9

Visualization

Tap to expand
Sum of Numbers With Units Digit KTarget: 58Units digit: 8Need digit: 9Numbers end in 919+39=58Minimum count: 2Both numbers end in 9, sum equals target
Understanding the Visualization
1
Input
Target sum num=58, required units digit k=9
2
Process
Find minimum numbers ending in 9 that sum to 58
3
Output
Return count=2 (using 19+39=58)
Key Takeaway
🎯 Key Insight: The units digit pattern of sums repeats every 10 numbers, enabling O(1) solution
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
856 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