Data Structures & AlgorithmsVery hardAccenture · Infosys OA

Problem: What is the time complexity of finding the lowest common ancestor (LCA) of two nodes in a binary tree with n nodes, using a single recursive DFS (no preprocessing)?

  1. A. O(1) after no preprocessing at all
  2. B. O(n) in the worst case, since the DFS may need to visit every node
  3. C. O(n^2), checking every pair of ancestors
  4. D. O(log n) always, regardless of tree shape

Correct answer: B. O(n) in the worst case, since the DFS may need to visit every node

Without preprocessing (like binary lifting or Euler-tour + sparse table), a direct recursive LCA search may need to explore the whole tree in the worst case (e.g. a skewed tree), giving O(n).

More Coding Interview Problems questions

Exams that ask this topic