[LeetCode] Smallest Greater Multiple Made of Two Digits

1999. Smallest Greater Multiple Made of Two Digits

Given three integers, k, digit1, and digit2, you want to find the smallest integer that is:

  • Larger than k,
  • A multiple of k, and
  • 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 (231 - 1), return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int findInteger(int k, int digit1, int digit2) {
priority_queue<long long, vector<long long>, greater<long long>> q;
unordered_set<long long> vis;

auto push = [&](long long n) {
if(vis.count(n)) return;
if(n > INT_MAX) return;
q.push(n);
vis.insert(n);
};

push(digit1);
push(digit2);

while(!q.empty()) {
auto u = q.top(); q.pop();
if(u > k and u % k == 0) return u;
push(u * 10 + digit1);
push(u * 10 + digit2);
}


return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/12/PS/LeetCode/smallest-greater-multiple-made-of-two-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.