Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A tree has n = 10⁵ nodes and arrives as a parent array. You must answer 10⁵ queries 'is u an ancestor of v?'. Which preprocessing makes each query O(1)?

  1. A. BFS from u for each query
  2. B. Store each node's depth and compare depths
  3. C. Sort nodes by value and binary search
  4. D. One DFS recording entry and exit times; u is an ancestor of v iff tin[u] ≤ tin[v] and tout[v] ≤ tout[u]

Correct answer: D. One DFS recording entry and exit times; u is an ancestor of v iff tin[u] ≤ tin[v] and tout[v] ≤ tout[u]

Euler-tour timestamps nest: a subtree occupies a contiguous interval of entry times. One O(n) DFS, then two comparisons per query. BFS per query is O(n) each (10¹⁰ total). Depth alone cannot tell whether v lies in u's subtree.

More Coding Interview Problems questions

Exams that ask this topic