Formatted question description: https://leetcode.ca/all/440.html

440. K-th Smallest in Lexicographical Order

Level

Hard

Description

Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.

Note: 1 ≤ k ≤ n ≤ 109.

Example:

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.

Solution

Starting from 1, let curr be the current prefix, and the next prefix is curr + 1. Count the number of integers with prefix curr. If the number of integers with prefix curr is greater than k, then set curr = curr * 10 and use the updated curr to calculate the next prefix curr + 1. Otherwise, subtract the number of integers from k, and set curr = curr + 1. Repeat the process until k becomes 0. Finally, return curr.

class Solution {
    public int findKthNumber(int n, int k) {
        int curr = 1;
        k--;
        while (k > 0) {
            int steps = getSteps(n, curr, curr + 1);
            if (steps > k) {
                curr *= 10;
                k--;
            } else {
                curr++;
                k -= steps;
            }
        }
        return curr;
    }

    public int getSteps(int n, long curr, long next) {
        int steps = 0;
        while (curr <= n) {
            steps += Math.min(n + 1, next) - curr;
            curr *= 10;
            next *= 10;
        }
        return steps;
    }
}

All Problems

All Solutions