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 K INPUT num = 58 k = 9 Target Sum: 58 0 58 Required Units Digit: 9 Numbers ending in 9: 9 19 29 ... Find min count summing to 58 ALGORITHM STEPS 1 Check Base Case If num=0, return 0 2 Try count 1 to 10 Units repeat every 10 3 Check Units Match (i * k) % 10 == num % 10 Finding min count for 58, k=9 i=1: 1*9=9 units=9 58%10=8 X i=2: 2*9=18 units=8 58%10=8 OK 29 + 29 = 58 (valid!) 2*9 <= 58, so return 2 4 Verify i*k <= num Ensure sum is achievable FINAL RESULT Minimum set size found: 2 The Set: 29 + 29 = 58 Verification: Units of 29 is 9 [OK] 29 + 29 = 58 [OK] Key Insight: Units digits cycle every 10 numbers (k, 2k, 3k... mod 10 repeats). We only need to check counts 1-10. For each count i, if (i*k)%10 equals num%10 and i*k <= num, we can form the sum. Return first valid i. TutorialsPoint - Sum of Numbers With Units Digit K | Optimal 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