Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #440: K-th Smallest in Lexicographical Order

In this guide, we solve Leetcode #440 K-th Smallest in Lexicographical Order in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Trie

Intuition

Prefix queries are most efficient with a trie.

Each character transitions to the next node in the tree.

Approach

Insert words into the trie and traverse by characters for queries.

Track terminal markers to distinguish full words from prefixes.

Steps:

  • Build the trie.
  • Traverse for each query.
  • Return matches or validations.

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.

Python Solution

class Solution: def findKthNumber(self, n: int, k: int) -> int: def count(curr): next, cnt = curr + 1, 0 while curr <= n: cnt += min(n - curr + 1, next - curr) next, curr = next * 10, curr * 10 return cnt curr = 1 k -= 1 while k: cnt = count(curr) if k >= cnt: k -= cnt curr += 1 else: k -= 1 curr *= 10 return curr

Complexity

The time complexity is O(log⁡2n)O(\log^2 n)O(log2n), as we perform logarithmic operations for counting and traversing the Trie structure. The space complexity is O(1)O(1)O(1) since we only use a few variables to track the current prefix and count.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy