Data Structures & AlgorithmsVery hardICPC regional · Product Company SDE
Problem: A tree has 7 nodes 1–7 with edges 1-2, 1-3, 2-4, 2-5, 3-6, 6-7. Each node is coloured red if its depth from node 1 is even and blue otherwise. How many pairs of nodes (unordered, distinct) have the same colour and are at distance exactly 2 in the tree?
- A. 9
- B. 6
- C. 12
- D. 21
Correct answer: B. 6
Nodes at distance 2 always have depths of the same parity, so the answer is just the number of distance-2 pairs: (1,4), (1,5), (1,6), (4,5), (2,3), (3,7) → 6. Counting all same-colour pairs gives 9, ordered pairs give 12, and 21 counts every pair.
More Coding Interview Problems questions
- Problem: Starting with the sorted list 1, 4, 9, 16, 25, 36, two operations alternate: first remove the largest element, then append the…
- Problem: A simple graph has 6 vertices labelled 1–6. Vertex i is adjacent to j exactly when gcd(i, j) = 1 and i ≠ j. How many edges does…
- Problem: What is the number of inversions in the array [6, 2, 8, 1, 9, 4, 3, 7, 5]? (An inversion is a pair of indices i < j with a[i] >…
- Problem: Using a single counter, a sequence of commands is applied to the value x = 0: "+5", "×2", "−3", "×2", "+1", "÷4" (integer…
- Problem: In a binary max-heap stored in an array with 1-based indexing, the array is [40, 30, 35, 10, 20, 25, 28, 5, 8, 12]. An operation…
- Problem: In the array [3, 8, 1, 9, 4, 7, 2, 6, 5], what is the length of the longest subarray whose sum is exactly 20?