Smallest Greater Multiple Made of Two Digits - Problem

Given three integers k, digit1, and digit2, find the smallest integer that satisfies all of the following conditions:

  • The integer is larger than k
  • The integer is a multiple of k
  • The integer is comprised of only the digits digit1 and/or digit2

Return the smallest such integer. If no such integer exists or the integer exceeds the limit of a signed 32-bit integer (2³¹ - 1 = 2147483647), return -1.

Input & Output

Example 1 — Basic Case
$ Input: k = 2, digit1 = 1, digit2 = 2
Output: 12
💡 Note: Numbers using digits 1,2: 1, 2, 11, 12, 21, 22... First number > 2 that's divisible by 2 is 12
Example 2 — Single Digit
$ Input: k = 3, digit1 = 4, digit2 = 2
Output: 24
💡 Note: Numbers using digits 4,2: 2, 4, 22, 24, 42, 44... First number > 3 divisible by 3 is 24 (2+4=6, divisible by 3)
Example 3 — No Solution
$ Input: k = 2, digit1 = 3, digit2 = 5
Output: -1
💡 Note: All numbers made from digits 3,5 are odd, so none can be divisible by 2

Constraints

  • 1 ≤ k ≤ 500
  • 0 ≤ digit1 ≤ 9
  • 0 ≤ digit2 ≤ 9
  • digit1 ≠ digit2

Visualization

Tap to expand
Smallest Greater Multiple Made of Two Digits INPUT k = 2 (target divisor) 1 digit1 2 digit2 BFS Queue Start: 1 2 Constraints: - Result > k - Result % k == 0 - Only digits 1, 2 - Within 32-bit ALGORITHM STEPS 1 Initialize BFS Start with digit1, digit2 2 Process Queue Dequeue, check conditions 3 Generate Next num*10+d1, num*10+d2 4 Check & Return If valid multiple found BFS Exploration: 1 2 11 12 21 22 OK! 12 % 2 == 0 12 > 2 FINAL RESULT 12 Output Verification: - 12 > 2 OK - 12 % 2 = 0 OK - Digits: 1, 2 OK - Within 32-bit OK 12 is the smallest multiple of 2 using only digits 1 and 2 that is greater than 2 Key Insight: BFS guarantees we find the smallest valid number first because we explore numbers level by level (by digit count). Using modular arithmetic, we only track remainders to avoid redundant states. Time: O(k) states, each with 2 transitions. Space: O(k) for visited remainders and queue. TutorialsPoint - Smallest Greater Multiple Made of Two Digits | BFS with Modular Arithmetic
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~25 min Avg. Time
425 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