Data Structures & AlgorithmsModerateProduct Company SDE · tree round
Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code.
Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code.
import sys
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
g = {i: [] for i in range(6)}
for u, v in edges:
g[u].append(v)
g[v].append(u)
def size(u, p):
s = 1
for v in g[u]:
if v != p:
s += size(v, u)
return s
print(size(1, 0))What is printed?- A. 2
- B. 4
- C. 5
- D. 3
Correct answer: D. 3
The subtree of 1 contains 1, 3 and 4. Passing the parent avoids walking back up the tree.
More Coding Interview Problems questions
- Problem: Which statement about Fenwick (binary indexed) trees is false?
- Problem: Items have small values (at most 1000 each, n = 100) but very large weights (up to 10^9), and capacity W = 10^9. Which DP is…
- Problem: For n = 10^5 elements and q = 10^5 queries, a sqrt-decomposition answers each query in O(sqrt n). Roughly how many elementary…
- Problem: How many scalar multiplications does the naive product of a 3 x 4 matrix and a 4 x 2 matrix need?
- Problem: Using the cost of a spanning tree on the complete graph K4 (Cayley's formula n^(n-2)), how many spanning trees does K4 have?
- Problem: How many decimal palindromes lie in [1, 1000]? Run the code. python print(sum(1 for x in range(1, 1001) if str(x) ==…