K th Smallest in Lexicographical Order

This page explains Java solution to problem K th Smallest in Lexicographical Order using Math.

Problem Statement

Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to 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.

Solution

If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

class KThSmallestInLexicographicalOrder {
    public int findKthNumber(int n, int k) {
        long current = 1;
        k = k - 1;
        while(k > 0) {
            int steps = calculateSteps(n, current, current + 1);
            if(k >= steps) {
                k -= steps;
                current = current + 1;
            }
            else {
                k--;
                current = current * 10;
            }
        }
        return (int)current;
    }

    private int calculateSteps(int n, long n1, long n2) {
        int steps = 0;
        while(n1 <= n) {
            steps += Math.min(n + 1, n2) - n1;
            n1 *= 10;
            n2 *= 10;
        }
        return steps;
    }
}

Time Complexity

O(K * log N)) Where
K is index of smallest integer that we have to find.
N is Upper bound

Space Complexity

O(1)