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
tobi
is a sequence of distinct nodes starting with nodeai
and ending with nodebi
such that every two adjacent nodes in the sequence share an edge in the tree.
Return an arrayanswer
of lengthm
where answer[i]
is the answer to the ith
query.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= n <= 10^4
edges.length == n - 1
edges[i].length == 3
0 <= ui, vi < n
1 <= wi <= 26
- The input is generated such that
edges
represents a valid tree. 1 <= queries.length == m <= 2 * 10^4
queries[i].length == 2
0 <= ai, bi < n
Solution
Method 1 – Path Frequency Counting with LCA
Intuition
For each query, we need to find the path between two nodes and count the frequency of each edge weight on that path. The minimum number of operations is the number of edges minus the maximum frequency of any weight on the path. To efficiently find the path and its weights, we use Lowest Common Ancestor (LCA) and prefix frequency arrays for each node.
Approach
- Build the tree as an adjacency list, storing edge weights.
- Preprocess the tree with DFS to record parent, depth, and prefix frequency of edge weights for each node.
- For each query, find the LCA of the two nodes.
- For each possible weight, calculate its frequency on the path using prefix frequency arrays and the LCA.
- The answer for each query is the path length minus the maximum frequency found.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O((n + m) * log n + m * k)
, where n is the number of nodes, m is the number of queries, and k is the number of possible weights (<=26). Each query is processed in O(log n + k). - 🧺 Space complexity:
O(n * k)
, for prefix frequency arrays and LCA tables.