KatInterview

440. K-th Smallest in Lexicographical Order

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the k-th smallest integer in the range [1, n] when sorted lexicographically. Lexicographical order means numbers are sorted as if they were strings (e.g., 10 comes before 2). A brute-force approach of generating all numbers and sorting them is infeasible due to the large constraint on n (up to 10^9).

Solution

K-th Smallest in Lexicographical Order in Python

class Solution:
    def findKthNumber(self, n: int, k: int) -> int:
        
        def calc_steps(n1: int, n2: int) -> int:
            """
            Calculates the number of integers in the range [1, n] that
            have a prefix lexicographically between n1 (inclusive) and n2 (exclusive).
            """
            steps = 0
            while n1 <= n:
                # Add the number of nodes at the current level.
                # This is the count of numbers in the interval [n1, n2-1] that are <= n.
                steps += min(n + 1, n2) - n1
                
                # Move to the next level.
                n1 *= 10
                n2 *= 10
            return steps

        current = 1
        k -= 1  # 1 is the first number, so we need k-1 more steps

        while k > 0:
            # Calculate how many numbers are lexicographically between current and current+1.
            steps = calc_steps(current, current + 1)
            
            if steps <= k:
                # The k-th number is not in the subtree of 'current'.
                # Skip all numbers with prefix 'current'.
                k -= steps
                # Move to the next sibling.
                current += 1
            else:
                # The k-th number is in the subtree of 'current'.
                # Move down to the first child. This is one step.
                k -= 1
                current *= 10
                
        return current

K-th Smallest in Lexicographical Order in Java

class Solution {
    public int findKthNumber(int n, int k) {
        long current = 1;
        k--; // 1 is the first number, so we need k-1 more steps

        while (k > 0) {
            // Calculate how many numbers are in the lexicographical range [current, current+1)
            // which are less than or equal to n.
            long steps = calcSteps(n, current, current + 1);
            
            if (steps <= k) {
                // The k-th number is not in the subtree of 'current'.
                // Skip all numbers with prefix 'current'.
                k -= steps;
                // Move to the next sibling.
                current++;
            } else {
                // The k-th number is in the subtree of 'current'.
                // Move down to the first child. This is one step.
                k--;
                current *= 10;
            }
        }
        return (int)current;
    }

    // Calculates the number of integers in the range [1, n] that
    // have a prefix lexicographically between n1 (inclusive) and n2 (exclusive).
    private long calcSteps(long n, long n1, long n2) {
        long steps = 0;
        while (n1 <= n) {
            // Add the number of nodes at the current level.
            // This is the count of numbers in the interval [n1, n2-1] that are <= n.
            steps += Math.min(n + 1, n2) - n1;
            
            // Move to the next level.
            n1 *= 10;
            n2 *= 10;
        }
        return steps;
    }
}

K-th Smallest in Lexicographical Order in C++

class Solution {
public:
    int findKthNumber(int n, int k) {
        long long current = 1;
        k--; // 1 is the first number, so we need k-1 more steps

        while (k > 0) {
            // Calculate how many numbers are in the lexicographical range [current, current+1)
            // which are less than or equal to n.
            long long steps = calcSteps(n, current, current + 1);

            if (steps <= k) {
                // The k-th number is not in the subtree of 'current'.
                // Skip all numbers with prefix 'current'.
                k -= steps;
                // Move to the next sibling.
                current++;
            } else {
                // The k-th number is in the subtree of 'current'.
                // Move down to the first child. This is one step.
                k--;
                current *= 10;
            }
        }
        return current;
    }

private:
    // Calculates the number of integers in the range [1, n] that
    // have a prefix lexicographically between n1 (inclusive) and n2 (exclusive).
    // This effectively counts all nodes in the subtrees rooted from n1 up to (but not including) n2.
    long long calcSteps(long long n, long long n1, long long n2) {
        long long steps = 0;
        while (n1 <= n) {
            // Add the number of nodes at the current level.
            // This is the count of numbers in the interval [n1, n2-1] that are <= n.
            steps += std::min(n + 1, n2) - n1;
            
            // Move to the next level.
            n1 *= 10;
            n2 *= 10;
        }
        return steps;
    }
};

K-th Smallest in Lexicographical Order in TypeScript

function findKthNumber(n: number, k: number): number {

    const calcSteps = (n1: number, n2: number): number => {
        /**
         * Calculates the number of integers in the range [1, n] that
         * have a prefix lexicographically between n1 (inclusive) and n2 (exclusive).
         */
        let steps = 0;
        while (n1 <= n) {
            // Add the number of nodes at the current level.
            // This is the count of numbers in the interval [n1, n2-1] that are <= n.
            steps += Math.min(n + 1, n2) - n1;

            // Move to the next level.
            n1 *= 10;
            n2 *= 10;
        }
        return steps;
    };

    let current = 1;
    k -= 1; // 1 is the first number, so we need k-1 more steps

    while (k > 0) {
        // Calculate how many numbers are in the lexicographical range [current, current+1)
        // which are less than or equal to n.
        const steps = calcSteps(current, current + 1);

        if (steps <= k) {
            // The k-th number is not in the subtree of 'current'.
            // Skip all numbers with prefix 'current'.
            k -= steps;
            // Move to the next sibling.
            current += 1;
        } else {
            // The k-th number is in the subtree of 'current'.
            // Move down to the first child. This is one step.
            k -= 1;
            current *= 10;
        }
    }
    
    return current;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.