GATE / CS ARCHIVE

SIMILAR QUESTIONS / DATA STRUCTURES

Bound pruned balanced-BST range traversal

2 questions solved the same way, newest first. Back to Data Structures

How these are solved

Search interval boundaries then traverse only matching keys and boundary paths; derive O(log n + output count), summing or reporting each matching key. Aggregation without augmentation and reporting have the same traversal but different outputs.

2 marks · MCQ
Report issue

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).
Tap to enlarge
Your answer
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.

Original paper, page 13 · Answer key

2 marks · NAT
Report issue

Binary Search & Balanced Trees

Question 39, GATE 2014: An unaugmented balanced BST T stores n numbers. There are m keys in the interval from L to H, whose sum must be computed. If the tightest upper bound is O(nᵃ logᵇ n + mᶜ logᵈ n), find a+10b+100c+1000d.
Tap to enlarge
Answer & solution

Official answer: 110

Step 1: Use the search ordering to locate the interval's first relevant key or its boundary in O(log n), since the tree is balanced. Step 2: Traverse the m matching keys in inorder while pruning subtrees wholly outside the interval. With a traversal stack, the total is O(log n+m), not m independent root-to-key searches costing O(m log n). Step 3: Match this to the displayed form: n⁰log¹n + m¹log⁰n, so (a,b,c,d)=(0,1,1,0). The requested encoding is 0+10+100+0=110. Subtree-sum augmentation was not specified and would change the range-sum method.

Original paper, page 61 · Answer key