Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following:
u and v such that there exists an edge [u, v] in the tree.u is the parent of v in the tree.Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj.
Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his guesses are true.
Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice's tree. If there is no such tree, return 0.
Example 1:
Input: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3 Output: 3 Explanation: Root = 0, correct guesses = [1,3], [0,1], [2,4] Root = 1, correct guesses = [1,3], [1,0], [2,4] Root = 2, correct guesses = [1,3], [1,0], [2,4] Root = 3, correct guesses = [1,0], [2,4] Root = 4, correct guesses = [1,3], [1,0] Considering 0, 1, or 2 as root node leads to 3 correct guesses.
Example 2:
Input: edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1 Output: 5 Explanation: Root = 0, correct guesses = [3,4] Root = 1, correct guesses = [1,0], [3,4] Root = 2, correct guesses = [1,0], [2,1], [3,4] Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4] Root = 4, correct guesses = [1,0], [2,1], [3,2] Considering any node as root will give at least 1 correct guess.
Constraints:
edges.length == n - 12 <= n <= 1051 <= guesses.length <= 1050 <= ai, bi, uj, vj <= n - 1ai != biuj != vjedges represents a valid tree.guesses[j] is an edge of the tree.guesses is unique.0 <= k <= guesses.lengthProblem summary: Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following: Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree. He tells Alice that u is the parent of v in the tree. Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj. Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his guesses are true. Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice's tree.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Tree
[[0,1],[1,2],[1,3],[4,2]] [[1,3],[0,1],[1,0],[2,4]] 3
[[0,1],[1,2],[2,3],[3,4]] [[1,0],[3,4],[2,1],[3,2]] 1
closest-node-to-path-in-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2581: Count Number of Possible Root Nodes
class Solution {
private List<Integer>[] g;
private Map<Long, Integer> gs = new HashMap<>();
private int ans;
private int k;
private int cnt;
private int n;
public int rootCount(int[][] edges, int[][] guesses, int k) {
this.k = k;
n = edges.length + 1;
g = new List[n];
Arrays.setAll(g, e -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
for (var e : guesses) {
int a = e[0], b = e[1];
gs.merge(f(a, b), 1, Integer::sum);
}
dfs1(0, -1);
dfs2(0, -1);
return ans;
}
private void dfs1(int i, int fa) {
for (int j : g[i]) {
if (j != fa) {
cnt += gs.getOrDefault(f(i, j), 0);
dfs1(j, i);
}
}
}
private void dfs2(int i, int fa) {
ans += cnt >= k ? 1 : 0;
for (int j : g[i]) {
if (j != fa) {
int a = gs.getOrDefault(f(i, j), 0);
int b = gs.getOrDefault(f(j, i), 0);
cnt -= a;
cnt += b;
dfs2(j, i);
cnt -= b;
cnt += a;
}
}
}
private long f(int i, int j) {
return 1L * i * n + j;
}
}
// Accepted solution for LeetCode #2581: Count Number of Possible Root Nodes
func rootCount(edges [][]int, guesses [][]int, k int) (ans int) {
n := len(edges) + 1
g := make([][]int, n)
gs := map[int]int{}
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
f := func(i, j int) int {
return i*n + j
}
for _, e := range guesses {
a, b := e[0], e[1]
gs[f(a, b)]++
}
cnt := 0
var dfs1 func(i, fa int)
var dfs2 func(i, fa int)
dfs1 = func(i, fa int) {
for _, j := range g[i] {
if j != fa {
cnt += gs[f(i, j)]
dfs1(j, i)
}
}
}
dfs2 = func(i, fa int) {
if cnt >= k {
ans++
}
for _, j := range g[i] {
if j != fa {
a, b := gs[f(i, j)], gs[f(j, i)]
cnt -= a
cnt += b
dfs2(j, i)
cnt -= b
cnt += a
}
}
}
dfs1(0, -1)
dfs2(0, -1)
return
}
# Accepted solution for LeetCode #2581: Count Number of Possible Root Nodes
class Solution:
def rootCount(
self, edges: List[List[int]], guesses: List[List[int]], k: int
) -> int:
def dfs1(i, fa):
nonlocal cnt
for j in g[i]:
if j != fa:
cnt += gs[(i, j)]
dfs1(j, i)
def dfs2(i, fa):
nonlocal ans, cnt
ans += cnt >= k
for j in g[i]:
if j != fa:
cnt -= gs[(i, j)]
cnt += gs[(j, i)]
dfs2(j, i)
cnt -= gs[(j, i)]
cnt += gs[(i, j)]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
gs = Counter((u, v) for u, v in guesses)
cnt = 0
dfs1(0, -1)
ans = 0
dfs2(0, -1)
return ans
// Accepted solution for LeetCode #2581: Count Number of Possible Root Nodes
use std::usize;
/**
* [2581] Count Number of Possible Root Nodes
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashSet;
impl Solution {
pub fn root_count(edges: Vec<Vec<i32>>, guesses: Vec<Vec<i32>>, k: i32) -> i32 {
let mut graph = vec![vec![]; edges.len() + 1];
for edge in edges {
let x = edge[0] as usize;
let y = edge[1] as usize;
graph[x].push(y);
graph[y].push(x);
}
let mut guess_set = HashSet::with_capacity(guesses.len());
for guess in guesses {
guess_set.insert(Solution::hash(guess[0] as usize, guess[1] as usize));
}
let mut count = 0;
Solution::dfs(&graph, &guess_set, 0, usize::MAX, &mut count);
dbg!(count);
let mut result = 0;
Solution::tree_dp(&graph, &guess_set, &k, 0, usize::MAX, count, &mut result);
result
}
fn hash(x: usize, y: usize) -> i64 {
(x as i64) * 1000000 + (y as i64)
}
fn dfs(
graph: &Vec<Vec<usize>>,
guess_set: &HashSet<i64>,
now: usize,
pre: usize,
count: &mut i32,
) {
for next in &graph[now] {
let next = *next;
if next == pre {
continue;
}
if guess_set.contains(&Solution::hash(now, next)) {
*count += 1;
}
Solution::dfs(graph, guess_set, next, now, count);
}
}
fn tree_dp(
graph: &Vec<Vec<usize>>,
guess_set: &HashSet<i64>,
k: &i32,
now: usize,
pre: usize,
count: i32,
result: &mut i32,
) {
if count >= *k {
*result += 1;
}
for next in &graph[now] {
let next = *next;
if next == pre {
continue;
}
let mut count = count;
if guess_set.contains(&Solution::hash(now, next)) {
count -= 1;
}
if guess_set.contains(&Solution::hash(next, now)) {
count += 1;
}
Solution::tree_dp(graph, guess_set, k, next, now, count, result);
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2581() {
assert_eq!(
Solution::root_count(
vec![vec![0, 1], vec![1, 2], vec![1, 3], vec![4, 2]],
vec![vec![1, 3], vec![0, 1], vec![1, 0], vec![2, 4]],
3
),
3
);
assert_eq!(
Solution::root_count(
vec![
vec![0, 1],
vec![2, 0],
vec![0, 3],
vec![4, 2],
vec![3, 5],
vec![6, 0],
vec![1, 7],
vec![2, 8],
vec![2, 9],
vec![4, 10],
vec![9, 11],
vec![3, 12],
vec![13, 8],
vec![14, 9],
vec![15, 9],
vec![10, 16]
],
vec![vec![8, 2], vec![12, 3], vec![0, 1], vec![16, 10]],
2
),
4
);
}
}
// Accepted solution for LeetCode #2581: Count Number of Possible Root Nodes
function rootCount(edges: number[][], guesses: number[][], k: number): number {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
const gs: Map<number, number> = new Map();
const f = (i: number, j: number) => i * n + j;
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
for (const [a, b] of guesses) {
const x = f(a, b);
gs.set(x, gs.has(x) ? gs.get(x)! + 1 : 1);
}
let ans = 0;
let cnt = 0;
const dfs1 = (i: number, fa: number): void => {
for (const j of g[i]) {
if (j !== fa) {
cnt += gs.get(f(i, j)) || 0;
dfs1(j, i);
}
}
};
const dfs2 = (i: number, fa: number): void => {
ans += cnt >= k ? 1 : 0;
for (const j of g[i]) {
if (j !== fa) {
const a = gs.get(f(i, j)) || 0;
const b = gs.get(f(j, i)) || 0;
cnt -= a;
cnt += b;
dfs2(j, i);
cnt -= b;
cnt += a;
}
}
};
dfs1(0, -1);
dfs2(0, -1);
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.