Skip to content

Commit 24ce041

Browse files
committed
Add solution #440
1 parent c73e6f9 commit 24ce041

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,7 @@
349349
436|[Find Right Interval](./0436-find-right-interval.js)|Medium|
350350
437|[Path Sum III](./0437-path-sum-iii.js)|Medium|
351351
438|[Find All Anagrams in a String](./0438-find-all-anagrams-in-a-string.js)|Medium|
352+
440|[K-th Smallest in Lexicographical Order](./0440-k-th-smallest-in-lexicographical-order.js)|Hard|
352353
441|[Arranging Coins](./0441-arranging-coins.js)|Easy|
353354
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
354355
443|[String Compression](./0443-string-compression.js)|Medium|
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 440. K-th Smallest in Lexicographical Order
3+
* https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/
4+
* Difficulty: Hard
5+
*
6+
* Given two integers n and k, return the kth lexicographically smallest integer in
7+
* the range [1, n].
8+
*/
9+
10+
/**
11+
* @param {number} n
12+
* @param {number} k
13+
* @return {number}
14+
*/
15+
var findKthNumber = function(n, k) {
16+
let result = 1;
17+
k--;
18+
19+
while (k > 0) {
20+
let count = 0;
21+
for (let first = result, last = result + 1; first <= n; first *= 10, last *= 10) {
22+
count += Math.min(n + 1, last) - first;
23+
}
24+
25+
if (count <= k) {
26+
result++;
27+
k -= count;
28+
} else {
29+
result *= 10;
30+
k--;
31+
}
32+
}
33+
34+
return result;
35+
};

0 commit comments

Comments
 (0)