Data Structures & AlgorithmsVery hardProduct company OA
In the tree with edges 1–2, 1–3, 2–4, 2–5, 3–6, 5–7, the rerooting technique computes S(v) = sum of distances from v to every other node. What are S(1) and S(5)?
- A. S(1) = 11, S(5) = 15
- B. S(1) = 10, S(5) = 13
- C. S(1) = 11, S(5) = 11
- D. S(1) = 11, S(5) = 13
Correct answer: D. S(1) = 11, S(5) = 13
From 1 the distances to 2, 3, 4, 5, 6, 7 are 1, 1, 2, 2, 2, 3 → S(1) = 11. Rerooting: moving the root from parent p to child c gives S(c) = S(p) + n − 2·size(c), with n = 7. size(2) = 4 → S(2) = 11 + 7 − 8 = 10; size(5) = 2 → S(5) = 10 + 7 − 4 = 13. Direct check from 5: 1 + 1 + 2 + 2 + 3 + 4 = 13. Rerooting with + 2·size instead of − gives the wrong values.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Each node of this binary tree holds a value; how many DOWNWARD paths (starting at any node, moving only to children, ending at any node)…
- Weighted undirected graph: A–B 1, B–C 2, C–D 3, D–A 4, A–C 5, B–D 6. The MST is unique. What is the weight of the SECOND-best spanning…
- Word ladder: change one letter at a time, every intermediate word must be in the dictionary {cold, cord, card, ward, warm, word, worm…
- In this grid, how many islands of 1s are there with 4-directional connectivity, and how many with 8-directional (diagonals also connect)?…
- What is the maximum path sum in this binary tree, where a path joins any two nodes along parent–child links and need not pass through the…
- A binary trie over 4-bit numbers finds the maximum XOR of any pair from [3, 10, 5, 9, 2, 8]. What is the maximum XOR?