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)?
- A. BFS from u for each query
- B. Store each node's depth and compare depths
- C. Sort nodes by value and binary search
- 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
- Problem: A tree of n nodes is stored as a skewed BST (keys inserted in increasing order). What is the cost of the recursive height…
- Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). Trees are built by build(xs): a…
- Problem: Return the vertical sum of a tree for every column, left to right (root column 0, left child −1, right child +1). Trees are built…
- Problem: Find the minimum depth (nodes on the shortest root-to-LEAF path). The candidate below is buggy. Trees are built by build(xs): a…
- Problem: Insert keys into an empty BST in the given order and report the preorder traversal. python def insert(t, k): if t is None: return…
- Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder…