Binary Search & Balanced Trees
![Question 41, GATE 2020: A balanced BST holds n keys. Reporting all keys in [a,b] produces k outputs. What is the optimal worst-case complexity? A Θ(log n); B Θ(log n+k); C Θ(k log n); D Θ(n log k).](../../../assets/questions/CS-2020-Q51-1.webp)
Answer & solution
Official answer: B
Worked explanation
A pruned inorder routine is: if node is null return; if key>a recurse left; if a≤key≤b output key; if key<b recurse right. With distinct keys, subtrees excluded by the interval are not scanned. Nodes visited without being reported lie along at most the two boundary-search paths, of height O(log n); every other visited node contributes an output. Thus a single traversal costs O(log n+k). Performing a fresh root-to-key successor search for each result would give an avoidable O(k log n). For a lower bound, a query locating a narrow boundary can require logarithmic comparisons and actually emitting k keys needs k operations.
Derivation and answer
Search down the balanced BST to find the lower bound a in O(log n). Then enumerate successive in-range keys with an inorder traversal, pruning subtrees entirely outside the interval. Boundary paths cost O(log n) and reported nodes cost O(k), so the total is O(log n+k). A worst-case boundary search needs logarithmic comparisons and reporting k distinct results needs Ω(k) output work. Thus the optimal worst-case bound is Θ(log n+k), B.
