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 ai to bi is a sequence of distinct nodes starting with node ai and ending with node bi such 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
Tree Edge Weight Equilibrium Problem0123131Query: Find path from node 0 to node 3Path: 0 → 1 → 2 → 3Edge weights: [1, 3, 1]Weight 1: appears 2 timesWeight 3: appears 1 timeKeep weight 1 (most frequent), change weight 3Result: 1 operation needed
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.
Asked in
Google 25 Amazon 18 Microsoft 15
8.8K Views
Medium Frequency
~25 min Avg. Time
342 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