[LeetCode] K-th Smallest in Lexicographical Order

440. K-th Smallest in Lexicographical Order

Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int findKthNumber(int n, int k) {
long long res = 1;
while(k != 1) {
int count = 0;
for(long long first = res, last = res + 1; first <= n; first *= 10, last *= 10) {
count += (min(n + 1ll, last) - first);
}
if(count < k) {
k -= count;
++res;
} else {
--k;
res *= 10;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/25/PS/LeetCode/k-th-smallest-in-lexicographical-order/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.