Minimum Edge Weight Equilibrium Queries in a Tree - Problem
There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates that there is an edge between nodes ui and vi with weight wi in the tree.
You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, find the minimum number of operations required to make the weight of every edge on the path from ai to bi equal. In one operation, you can choose any edge of the tree and change its weight to any value.
Note that:
- Queries are independent of each other, meaning that the tree returns to its initial state on each new query.
- The path from
aitobiis a sequence of distinct nodes starting with nodeaiand ending with nodebisuch that every two adjacent nodes in the sequence share an edge in the tree.
Return an array answer of length m where answer[i] is the answer to the ith query.
Input & Output
Example 1 — Basic Tree Query
$
Input:
n = 4, edges = [[0,1,1],[1,2,3],[2,3,1]], queries = [[0,3]]
›
Output:
[1]
💡 Note:
Path from 0 to 3 is: 0→1→2→3 with weights [1,3,1]. Weight 1 appears twice, weight 3 appears once. Keep weight 1, change weight 3. Answer: 3-2 = 1 operation.
Example 2 — Multiple Queries
$
Input:
n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[3,4,2]], queries = [[0,4],[1,3]]
›
Output:
[2,1]
💡 Note:
Query [0,4]: Path weights [1,1,2,2]. Weights 1 and 2 each appear twice, keep either, change 2 others. Query [1,3]: Path weights [1,2]. Different weights, change 1 of them.
Example 3 — Same Node Query
$
Input:
n = 3, edges = [[0,1,5],[1,2,3]], queries = [[1,1]]
›
Output:
[0]
💡 Note:
Query from node 1 to itself has empty path, so 0 operations needed.
Constraints
- 1 ≤ n ≤ 104
- edges.length == n - 1
- edges[i].length == 3
- 0 ≤ ui, vi ≤ n - 1
- 1 ≤ wi ≤ 26
- 1 ≤ queries.length ≤ 2 × 104
- 0 ≤ ai, bi ≤ n - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Tree with weighted edges and query nodes
2
Find Path
Use DFS to find unique path between query nodes
3
Count & Optimize
Count weight frequencies, keep most common
Key Takeaway
🎯 Key Insight: In a tree, there's exactly one path between any two nodes - find it, count weight frequencies, and keep the most common weight unchanged.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code