Data Structures & AlgorithmsEasyInfosys SP/DSE · Product Company SDE

Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity, where h is the tree height?

  1. A. O(n) – an inorder traversal is always required
  2. B. O(h) – walk down one path, going left or right by comparing with the target
  3. C. O(n log n) – sort the values first
  4. D. O(1) – the root is always closest

Correct answer: B. O(h) – walk down one path, going left or right by comparing with the target

At each node, the closest value can only be on the side towards the target, so one root-to-leaf walk with a running best suffices: O(h), which is O(log n) for a balanced tree and O(n) for a skewed one.

More Coding Interview Problems questions

Exams that ask this topic