Taro Logo

Minimum Edge Weight Equilibrium Queries in a Tree

#9 Most AskedHard
0 views
Topics:
TreesGraphs

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.

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 <= 104
  • 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 * 104
  • queries[i].length == 2
  • 0 <= ai, bi < n

Solution


Clarifying Questions

When 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:

  1. What is the range of possible edge weights in the tree?
  2. Can a query consist of a path from a node to itself, and if so, what is the expected output?
  3. What are the constraints on the number of nodes in the tree and the number of queries?
  4. Is the output for each query expected as a single integer representing the minimum changes needed, and should the results be returned in an array matching the order of the queries?
  5. Are edge weights guaranteed to be positive integers, or can they be zero or negative?

Brute Force Solution

Approach

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:

  1. Begin by looking at the first question about traveling between two specific locations.
  2. Trace every single possible route that connects the starting location to the ending location, even the ones that loop around or go the long way.
  3. For every route you trace, carefully write down the lengths of all the road segments that make up that exact path.
  4. Count up how many times each different road length appears on that particular path.
  5. Figure out how many road lengths you would need to change so that all the road lengths on this path become identical, aiming to change the fewest number of roads possible.
  6. Repeat this entire path-tracing and counting process for every other possible route between those two starting and ending locations.
  7. Compare the results from all the routes you explored and find the one that requires changing the fewest number of road lengths.
  8. Move on to the next question and repeat the exact same exhaustive process from the beginning until you have answered all the questions.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(q * n * d) – For each of the q queries, the brute force strategy exhaustively traces every possible route between the start and end locations, where the number of possible routes and path lengths in a tree with n nodes can be up to O(n) or bounded by tree depth d. For every single traced path, we must iterate through all its segments to count road lengths and determine the minimum changes required. This repetitive exhaustive path-tracing across q queries leads to approximately q * (n paths * n segments) operations, which simplifies to O(q * n squared) or O(q * n * d) depending on the tree structure.
Space Complexity
O(N log N + Q) – To support path tracing and queries between locations, we construct binary lifting tables of size N log N to efficiently find lowest common ancestors, along with prefix frequency arrays of size N log W to track road lengths, where N is the number of locations and Q is the number of queries. The recursive depth for tree preprocessing takes O(N) stack space, while the query results are stored in an output list of size Q. Combining these structures yields an overall auxiliary space complexity dominated by the preprocessing tables.

Optimal Solution

Approach

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:

  1. Build the tree and root it at node 0.
  2. Record each node's depth and how many times each edge weight appears on the path from the root.
  3. Fill a binary-lifting table of ancestors.
  4. For a query, find the lowest common ancestor of the two nodes.
  5. Add the two root-path counts and subtract the ancestor path twice to get the weights on the query path.
  6. Return the path length minus the highest weight count.

Code Implementation

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

Big(O) Analysis

Time Complexity
O((n + q) log n) – Building the ancestor table and answering each query both take a logarithmic number of jumps, with a constant pass over the 26 weights.
Space Complexity
O(n log n) – The binary-lifting table stores a logarithmic number of ancestors for every node.

Edge Cases

Tree with only a single node and no queries or queries on the same node
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Store weight frequencies compactly using sparse arrays or persistent segment trees aligned with tree paths.
0/45 completed