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)?
- A. O(1) after no preprocessing at all
- B. O(n) in the worst case, since the DFS may need to visit every node
- C. O(n^2), checking every pair of ancestors
- 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
- Problem: With O(n) preprocessing (Euler tour + sparse table for range-minimum query), LCA queries on a tree of n nodes can be answered in…
- Problem: Which statement correctly describes the diameter of a tree (the longest path between any two nodes) and how to compute it…
- Problem: A min-heap (binary heap) supports insert and extract-min in what time complexity, and what is the time to build a heap from n…
- Problem: To find the k largest elements among n numbers, which approach is asymptotically best when k is much smaller than n?
- Problem: An LRU (Least Recently Used) cache with O(1) get and put operations is classically implemented with which combination of data…
- Problem: Which statement about Kruskal's algorithm's overall time complexity is correct for a graph with V vertices and E edges?