Decode Algorithms & LeetCode
  • Decode Algorithms & LeetCode
  • G家练习
  • Array
    • Two Sum
    • Two Pointers
    • PrefixSum
    • Matrix
    • Interval & Sweepline
    • Sort
    • Iterator
    • Segment Tree
  • Binary Search
    • 教学
    • Binary Search on Matrix
    • Binary Search To Find An Answer
  • String
    • Parenthesis
    • Sliding Window
    • Trie
    • String arrangement
  • LinkedList
  • Tree
    • Level Order Traversal
    • BST or Inorder
    • Construst Tree
    • Prefix Tree
  • Stack
  • Heap
  • Greedy
  • BFS
  • DFS
    • DFS on String
    • Backtracking
    • DFS+Memo
  • Graph
    • Union Find
    • Topological Sort
    • Dijkstra
    • Bipartite Graph
    • Minimum Spanning Trees (MST)
    • Traveling Salesman Problem (TSP)
  • Dynamic Programing
    • DP on String
    • Knapsack Problem
  • Design
    • Concurrency
  • Math
  • Bit Manipulation
  • Divide & Conquer
Powered by GitBook
On this page

Was this helpful?

  1. Tree

Prefix Tree

PreviousConstrust TreeNextStack

Last updated 4 days ago

Was this helpful?

Role of countSteps

  • countSteps(n, prefix1, prefix2) counts numbers starting with prefix1 up to but not including prefix2, bounded by n.

  • It sums counts at every level of the prefix tree by multiplying prefix1 and prefix2 by 10 each time to move to the next level (deeper digits).

Summary:

  • The algorithm efficiently skips entire subtrees of the prefix tree based on step counts.

  • Moves horizontally (curr++) when the entire subtree is before k-th number.

  • Moves vertically (curr *= 10) to dive deeper into the prefix tree when the k-th number lies in that subtree.

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

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

// To count how many numbers exist between prefix1 and prefix2
private int countSteps(int n, long prefix1, long prefix2) {
    int steps = 0;
    while (prefix1 <= n) {
        steps += Math.min(prefix2, n + 1) - prefix1;
        prefix1 *= 10;
        prefix2 *= 10;
    }
    return steps;
}
440. K-th Smallest in Lexicographical Order