Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE
Problem: A rooted tree (root 1) has parent pointers: 2→1, 3→1, 4→2, 5→2, 6→4, 7→6, 8→3, 9→8. How many nodes lie on the path between node 7 and node 9 (both endpoints included)?
- A. 7
- B. 9
- C. 4
- D. 8
Correct answer: D. 8
The LCA of 7 and 9 is the root 1, so the path is 7-6-4-2-1-3-8-9: depth(7) + depth(9) − 2·depth(LCA) = 4 + 3 − 0 = 7 edges, hence 8 nodes. Reporting edges gives 7, counting every node in the tree gives 9, and 4 is just the depth of node 7.
More Coding Interview Problems questions
- Problem: For the complete binary tree with 10 nodes stored in heap order (node i has children 2i and 2i+1, root is node 1), what is the…
- Problem: Using the parent array par[i] for nodes 0–9 with par = [−1, 0, 0, 1, 1, 3, 3, 5, 6, 8], what is the 3rd ancestor of node 9 (the…
- Problem: Count the indices i of the string "abacaba" for which the suffix s[i:] is a palindrome.
- Problem: Deleting exactly one character from "aabca" produces some strings. How many distinct strings can result?
- Problem: Find the maximum sum of a strictly increasing subsequence of [1, 101, 2, 3, 100, 4, 5].
- Problem: How many subsets of {1, 2, ..., 8} contain no two consecutive integers (the empty set counts)?