0440. K-th Smallest in Lexicographical Order

https://leetcode.com/problems/k-th-smallest-in-lexicographical-order

Description

Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].

Example 1:

**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.

Example 2:

**Input:** n = 1, k = 1
**Output:** 1

Constraints:

  • 1 <= k <= n <= 109

ac

class Solution {
    public int findKthNumber(int n, int k) {
        int curr = 1;
        k--;

        while (k > 0) {
            int tmp = calStep(n,curr, curr+1);
            if (tmp <= k) {
                k -= tmp;
                curr++;
            } else {
                k -= 1;
                curr *= 10;
            }
        }

        return curr;
    }

    public int calStep(int n, int curr, int nxt) {
        int res = 0;
        while (curr <= n) {
            res += Math.min(n+1, nxt) - curr;
            curr *= 10;
            nxt *= 10;
        }
        return res;
    }
}

/*
1) tree with 10-nodes; 2) current value is 1, move (k-1) steps, curr will locate at the k-th smallest position, return it; 3) calculate steps between 2 adjacent nodes: calStep(), while curr <= n keep adding and curr *= 10
*/

Last updated