Skip to content

Commit 831b146

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (21.39%), Memory - 17.7 MB (64.68%)
1 parent 52507ff commit 831b146

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> n = 13, k = 2
8+
<strong>Output:</strong> 10
9+
<strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> n = 1, k = 1
16+
<strong>Output:</strong> 1
17+
</pre>
18+
19+
<p>&nbsp;</p>
20+
<p><strong>Constraints:</strong></p>
21+
22+
<ul>
23+
<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li>
24+
</ul>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Approach: Prefix tree
2+
3+
class Solution(object):
4+
def findKthNumber(self, n, k):
5+
curr = 1
6+
k -= 1
7+
8+
while k > 0:
9+
step = self._count_steps(n, curr, curr + 1)
10+
# If the steps are less than or equal to k, we skip this prefix's subtree
11+
if step <= k:
12+
# Move to the next prefix and decrease k by the number of steps we skip
13+
curr += 1
14+
k -= step
15+
else:
16+
# Move to the next level of the tree and decrement k by 1
17+
curr *= 10
18+
k -= 1
19+
20+
return curr
21+
22+
# To count how many numbers exist between prefix1 and prefix2
23+
def _count_steps(self, n, prefix1, prefix2):
24+
steps = 0
25+
while prefix1 <= n:
26+
steps += min(n + 1, prefix2) - prefix1
27+
prefix1 *= 10
28+
prefix2 *= 10
29+
return steps

0 commit comments

Comments
 (0)