Problem
Given two integers n
and k
, return the kth
lexicographically smallest integer in the range [1, n]
.
Example 1:
Input: n = 13, k = 2
Output: 10
Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
Example 2:
Input: n = 1, k = 1
Output: 1
Constraints:
1 <= k <= n <= 10^9
Solution (Java)
public class Solution {
public int findKthNumber(int n, int k) {
int curr = 1;
k = k - 1;
while (k > 0) {
int steps = calSteps(n, curr, curr + 1L);
if (steps <= k) {
curr += 1;
k -= steps;
} else {
curr *= 10;
k -= 1;
}
}
return curr;
}
// use long in case of overflow
private int calSteps(int n, long n1, long n2) {
long steps = 0;
while (n1 <= n) {
steps += Math.min(n + 1L, n2) - n1;
n1 *= 10;
n2 *= 10;
}
return (int) steps;
}
}
Solution (Javascript)
/**
* @param {number} n
* @param {number} k
* @return {number}
*/
var findKthNumber = function(n, k) {
let i, prefix = '';
while (k !== 0) {
for (i = 0; i <= 9; i++) {
const count = countForPrefix(n, prefix + i);
if (count < k)
k -= count;
else
break;
}
prefix = prefix + i;
k--; // number equal to prefix
}
return parseInt(prefix, 10);
};
// Calculates the amount of
// numbers <= n that starts with prefix.
function countForPrefix (n, prefix) {
let a = parseInt(prefix);
let b = a + 1;
if (a > n || a === 0)
return 0;
let res = 1;
a *= 10; b *= 10;
while (a <= n) {
res += Math.min(n + 1, b) - a;
a *= 10; b *= 10;
}
return res;
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).