In a balanced binary search tree with n elements, what is the worst case time complexity of reporting all elements in range [a, b]? Assume that the number of reported elements is k.

In a balanced binary search tree with n elements, what is the worst case time complexity of reporting all elements in range [a, b]? Assume that the number of reported elements is k. Correct Answer Θ(log n + k)

For the range , we first need to check if a and b are present in BST.

  1. Time complexity to check if element ‘a’ is present in BST = O(log n)
  2. Time complexity to check if element ‘b’ is present in BST = O(log n)

For finding all the elements in the range , we have to apply in-order sorting from a to b.

In this way, we will lay every successor of a reaching to the predecessor of b and all the elements between a and b will be reported.

For k elements, the in-order sorting will take O(k) time.

Hence, O(log n) + O(log n) + O(k) = O(2logn + k) = O(logn + k)

Related Questions