Count Number of Possible Root Nodes - Problem

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. If there is no such tree, return 0.

Input & Output

Example 1 — Basic Tree
$ Input: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
Output: 3
💡 Note: Tree has 5 nodes. Testing different roots: root 0 has 1 correct guess, root 1 has 3 correct guesses, root 2 has 3 correct guesses, others have fewer. So 3 possible roots meet k=3 requirement.
Example 2 — Small Tree
$ Input: edges = [[0,1],[0,2]], guesses = [[0,1]], k = 1
Output: 2
💡 Note: Simple tree with 3 nodes. Root 0 has 1 correct guess [0,1]. Root 1 or 2 as root would have 0 correct guesses. So 1 root meets k=1.
Example 3 — No Valid Root
$ Input: edges = [[0,1]], guesses = [[1,0]], k = 2
Output: 0
💡 Note: Only 2 nodes connected. At most 1 guess can be correct for any root, but k=2 requires at least 2 correct guesses. No valid root exists.

Constraints

  • n == edges.length + 1
  • 1 ≤ n ≤ 105
  • 1 ≤ guesses.length ≤ 105
  • 0 ≤ k ≤ guesses.length

Visualization

Tap to expand
Count Possible Root Nodes: Tree + Guesses → Valid RootsInput Tree012Bob's Guesses[0,1], [1,2]k = 2 requiredTest Each Root02 correct ✓11 correct ✗20 correct ✗Output: 1 valid root (node 0)Only root 0 achieves ≥ 2 correct parent-child guesses🎯 Key InsightTree rerooting avoids O(n²) rebuilding
Understanding the Visualization
1
Input
Tree edges and Bob's parent-child guesses with threshold k
2
Process
For each possible root, count matching parent-child relationships
3
Output
Number of roots where correct guesses ≥ k
Key Takeaway
🎯 Key Insight: Use tree rerooting DP to efficiently calculate correct guesses for all possible roots in O(n) time instead of O(n²) brute force
Asked in
Google 15 Facebook 12
12.5K Views
Medium Frequency
~25 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen