440. K-th Smallest in Lexicographical Order #587
-
Topics: Given two integers Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The idea is to traverse through numbers as they would appear in a lexicographical order, similar to performing a depth-first search (DFS) on a Trie. Approach:
Steps:
Let's implement this solution in PHP: 440. K-th Smallest in Lexicographical Order <?php
/**
* @param Integer $n
* @param Integer $k
* @return Integer
*/
function findKthNumber($n, $k) {
$current = 1; // Start with '1'
$k--; // Decrement k because we are starting with the first element
while ($k > 0) {
$steps = calculateSteps($n, $current, $current + 1);
if ($steps <= $k) {
// If the k-th number is not in this prefix, move to the next prefix
$current++;
$k -= $steps; // Decrease k by the number of steps skipped
} else {
// If the k-th number is in this prefix, move deeper in this branch
$current *= 10;
$k--; // We are considering the current number itself
}
}
return $current;
}
/**
* Helper function to calculate the number of steps between two prefixes in the range [1, n]
*
* @param $n
* @param $prefix1
* @param $prefix2
* @return int|mixed
*/
function calculateSteps($n, $prefix1, $prefix2) {
$steps = 0;
while ($prefix1 <= $n) {
$steps += min($n + 1, $prefix2) - $prefix1;
$prefix1 *= 10;
$prefix2 *= 10;
}
return $steps;
}
// Test cases
echo findKthNumber(13, 2); // Output: 10
echo "\n";
echo findKthNumber(1, 1); // Output: 1
?> Explanation:
Time Complexity:The time complexity is approximately This solution is efficient even for large inputs where |
Beta Was this translation helpful? Give feedback.
The idea is to traverse through numbers as they would appear in a lexicographical order, similar to performing a depth-first search (DFS) on a Trie.
Approach:
x
are10 * x + 0
,10 * x + 1
, ...,10 * x + 9
.1
, we explore numbers in lexicographical order, counting how many numbers can be placed before we reach thek
th one.start
andend
in a lexicographical order. This will help us skip some branches when needed.Steps:
1
.