Data Structures19 sections · 729 units
Open in Course

Kth Number: The Idea

Difference between versions

Core idea: if you have segment trees for prefixes, you can answer range queries by subtraction. Let TiT_i = segment tree counting elements in A[0..i1]A[0..i-1]. Count of value vv in range [l,r][l, r]: Tr+1[v]Tl[v]T_{r+1}[v] - T_l[v]. For kk-th smallest:

1.1. At each node, compute how many elements go to left subtree in range [l,r][l, r]

2.2. If kleftCountk \leq \text{leftCount}, answer is in left subtree

3.3. Otherwise, answer is in right subtree with kleftCountk - \text{leftCount}

This is binary search on the value space, guided by counts from two versions.