Algorithmskth smallest query
K-th Smallest Query (Efficiently Finding the K-th Smallest Element)
TT
Testlaa Team
May 15, 2026•1 min read
K-th smallest query is the standard persistent segtree application: query(l,r,k) after many array updates or static array.
Why this shows up in the real world
Time-series dashboards, game leaderboards, and competitive programming interval problems all need fast answers on changing arrays.
Core idea (explained for students)
Build persistent tree on value domain; each node stores count in value range for its index segment.
Try this in Python
def kth_smallest_brute(arr: list[int], l: int, r: int, k: int) -> int:
return sorted(arr[l : r + 1])[k - 1]
print(kth_smallest_brute([3, 1, 4, 1, 5], 0, 4, 3))
Common mistakes
- k larger than range length.
- Duplicate values—compress but keep stable ordering if needed.
Key takeaways
- Walk: if left_count ≥ k go left else k -= left_count, go right.
- Static array: merge sort tree alternative.
Tags:
Segment tree & range queriesPythonStudents
