LeetCode 440: K-th Smallest in Lexicographical Order Solution
Master LeetCode problem 440 (K-th Smallest in Lexicographical Order), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
440. K-th Smallest in Lexicographical Order
Problem Explanation
Explanation
To solve this problem efficiently, we can use a DFS-based approach to traverse the lexicographical order starting from 1. At each step, we calculate the count of numbers starting with the current prefix and compare it with the target k. Based on this comparison, we either move to the next prefix or go deeper into the tree structure of lexicographical numbers.
Algorithm:
- Initialize current as 1.
- For i from 1 to k-1:
- Calculate the count of numbers starting with the current prefix (current, current+1).
- If the count is less than k, update current to current+1.
- Otherwise, move to the next prefix by multiplying current by 10.
Time Complexity:
The time complexity of this approach is O(k) because we are iterating from 1 to k-1.
Space Complexity:
The space complexity is O(1) as we are not using any extra space apart from a few variables.
Solution Code
class Solution {
public int findKthNumber(int n, int k) {
int current = 1;
k--;
while (k > 0) {
int count = getCount(current, n);
if (count <= k) {
k -= count;
current++;
} else {
k--;
current *= 10;
}
}
return current;
}
private int getCount(int prefix, int n) {
long curr = prefix;
long next = curr + 1;
int count = 0;
while (curr <= n) {
count += Math.min(n + 1, next) - curr;
curr *= 10;
next *= 10;
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 440 (K-th Smallest in Lexicographical Order)?
This page provides optimized solutions for LeetCode problem 440 (K-th Smallest in Lexicographical Order) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 440 (K-th Smallest in Lexicographical Order)?
The time complexity for LeetCode 440 (K-th Smallest in Lexicographical Order) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 440 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 440 in Java, C++, or Python.