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:
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.
Example 1:
Input: n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]] Output: [0,0,1,3] Explanation: In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0. In the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0. In the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1. In the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from ai to bi.
Example 2:
Input: n = 8, edges = [[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = [[4,6],[0,4],[6,5],[7,4]] Output: [1,2,2,3] Explanation: In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1. In the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2. In the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2. In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from ai to bi.
Constraints:
1 <= n <= 104edges.length == n - 1edges[i].length == 30 <= ui, vi < n1 <= wi <= 26edges represents a valid tree.1 <= queries.length == m <= 2 * 104queries[i].length == 20 <= ai, bi < nWhen you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a map of connected locations with roads of various lengths, and people are constantly asking for the best way to travel between two points while balancing the lengths of the roads they use. The brute force strategy involves directly tracing every single possible path between the starting and ending locations for each question, looking at the lengths of every road along those paths, and figuring out how to change the most common road length to match the rest.
Here's how the algorithm would work step-by-step:
def min_operations_queries(number_nodes, edges, queries):
adjacency_list = [[] for node_index in range(number_nodes)]
for parent_node, child_node, edge_weight in edges:
adjacency_list[parent_node].append((child_node, edge_weight))
adjacency_list[child_node].append((parent_node, edge_weight))
# We explore all paths recursively to find every possible route between start and end nodes
def find_all_paths(current_node, target_node, visited_nodes, current_path_weights):
if current_node == target_node:
return [list(current_path_weights)]
visited_nodes.add(current_node)
collected_paths = []
for neighbor_node, edge_weight in adjacency_list[current_node]:
if neighbor_node not in visited_nodes:
current_path_weights.append(edge_weight)
sub_paths = find_all_paths(neighbor_node, target_node, visited_nodes, current_path_weights)
collected_paths.extend(sub_paths)
current_path_weights.pop()
visited_nodes.remove(current_node)
return collected_paths
answer_list = []
# We process each query independently by evaluating every single path between start and end
for start_node, end_node in queries:
all_possible_paths = find_all_paths(start_node, end_node, set(), [])
minimum_changes_needed = float('inf')
# We calculate minimum changes for a route by subtracting the most frequent weight from total edges
for path_weights in all_possible_paths:
if not path_weights:
minimum_changes_needed = 0
continue
weight_counts = {}
for weight in path_weights:
weight_counts[weight] = weight_counts.get(weight, 0) + 1
max_frequency = max(weight_counts.values())
changes_for_path = len(path_weights) - max_frequency
if changes_for_path < minimum_changes_needed:
minimum_changes_needed = changes_for_path
answer_list.append(minimum_changes_needed)
return answer_list
Making every edge on a path share one weight means changing every edge that does not already have the most common weight, so the answer is the path length minus that count. The tree is rooted at node 0, and each node stores how often each weight appears on the path from the root. A query adds the two root paths and removes the shared prefix up through their lowest common ancestor.
Here's how the algorithm would work step-by-step:
def min_operations_queries(node_count, edges, queries):
adjacency = [[] for _ in range(node_count)]
for start_node, end_node, edge_weight in edges:
adjacency[start_node].append((end_node, edge_weight))
adjacency[end_node].append((start_node, edge_weight))
ancestor_levels = 16
binary_parents = [[-1] * node_count for _ in range(ancestor_levels)]
node_depth = [0] * node_count
weight_counts = [[0] * 27 for _ in range(node_count)]
# Count edge weights on the path from the root to every node.
visit_stack = [0]
visited = [False] * node_count
visited[0] = True
while visit_stack:
current_node = visit_stack.pop()
for neighbor_node, edge_weight in adjacency[current_node]:
if visited[neighbor_node]:
continue
visited[neighbor_node] = True
binary_parents[0][neighbor_node] = current_node
node_depth[neighbor_node] = node_depth[current_node] + 1
weight_counts[neighbor_node] = weight_counts[current_node][:]
weight_counts[neighbor_node][edge_weight] += 1
visit_stack.append(neighbor_node)
# Double each ancestor pointer so a query can jump upward in logarithmic steps.
for level in range(1, ancestor_levels):
for node_index in range(node_count):
midpoint = binary_parents[level - 1][node_index]
if midpoint != -1:
binary_parents[level][node_index] = binary_parents[level - 1][midpoint]
def climb(node_index, distance):
for level in range(ancestor_levels):
if distance & (1 << level):
node_index = binary_parents[level][node_index]
return node_index
def lowest_common_ancestor(left_node, right_node):
if node_depth[left_node] < node_depth[right_node]:
left_node, right_node = right_node, left_node
left_node = climb(left_node, node_depth[left_node] - node_depth[right_node])
if left_node == right_node:
return left_node
for level in range(ancestor_levels - 1, -1, -1):
if binary_parents[level][left_node] != binary_parents[level][right_node]:
left_node = binary_parents[level][left_node]
right_node = binary_parents[level][right_node]
return binary_parents[0][left_node]
answers = []
for start_node, end_node in queries:
ancestor = lowest_common_ancestor(start_node, end_node)
path_length = node_depth[start_node] + node_depth[end_node] - 2 * node_depth[ancestor]
# Leaving the most common weight unchanged minimizes the edits on this path.
most_common = 0
for edge_weight in range(1, 27):
count = (
weight_counts[start_node][edge_weight]
+ weight_counts[end_node][edge_weight]
- 2 * weight_counts[ancestor][edge_weight]
)
if count > most_common:
most_common = count
answers.append(path_length - most_common)
return answers
| Case | How to Handle |
|---|---|
| Tree with only a single node and no queries or queries on the same node | Return zero changes because a path of length zero requires no edge weight modifications. |
| Edge weights are outside the typical small range specified in standard constraints | Coordinate compression or frequency counting per edge weight must be bounded to the exact allowed weight range. |
| Queries where the start and end nodes are identical | Return zero because a path from a node to itself contains no edges to modify. |
| Deeply skewed tree structures such as a linked list leading to deep recursion | Use iterative tree traversal or increase the recursion stack limit to prevent stack overflow errors during LCA computation. |
| Maximum possible number of nodes and queries leading to time limit exceeded | Precompute sparse tables for Lowest Common Ancestor and prefix frequency arrays of edge weights using binary lifting. |
| All edges along the queried path already have the exact same weight | The frequency table lookup will correctly identify the dominant weight and return a cost of zero changes. |
| Paths where all edge weights are completely distinct | Subtract the maximum frequency of any single weight from the total path length to yield the correct minimum changes. |
| Large scale queries causing excessive memory overhead when storing prefix frequency tables | Store weight frequencies compactly using sparse arrays or persistent segment trees aligned with tree paths. |