Taro Logo

Shortest Path in a Weighted Tree

Hard
Asked by:
Juspay
0 views
Topics:
TreesGraphs

You are given an integer n and an undirected, weighted tree rooted at node 1 with n nodes numbered from 1 to n. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates an undirected edge from node ui to vi with weight wi.

You are also given a 2D integer array queries of length q, where each queries[i] is either:

  • [1, u, v, w'] – Update the weight of the edge between nodes u and v to w', where (u, v) is guaranteed to be an edge present in edges.
  • [2, x] – Compute the shortest path distance from the root node 1 to node x.

Return an integer array answer, where answer[i] is the shortest path distance from node 1 to x for the ith query of [2, x].

Example 1:

Input: n = 2, edges = [[1,2,7]], queries = [[2,2],[1,1,2,4],[2,2]]

Output: [7,4]

Explanation:

  • Query [2, 2]: The shortest path from root node 1 to node 2 is 7.
  • Query [1, 1, 2, 4]: The weight of edge (1, 2) changes from 7 to 4.
  • Query [2, 2]: The shortest path from root node 1 to node 2 is 4.

Example 2:

Input: n = 3, edges = [[1,2,2],[1,3,4]], queries = [[2,1],[2,3],[1,1,3,7],[2,2],[2,3]]

Output: [0,4,2,7]

Explanation:

  • Query [2, 1]: The shortest path from root node 1 to node 1 is 0.
  • Query [2, 3]: The shortest path from root node 1 to node 3 is 4.
  • Query [1, 1, 3, 7]: The weight of edge (1, 3) changes from 4 to 7.
  • Query [2, 2]: The shortest path from root node 1 to node 2 is 2.
  • Query [2, 3]: The shortest path from root node 1 to node 3 is 7.

Example 3:

Input: n = 4, edges = [[1,2,2],[2,3,1],[3,4,5]], queries = [[2,4],[2,3],[1,2,3,3],[2,2],[2,3]]

Output: [8,3,2,5]

Explanation:

  • Query [2, 4]: The shortest path from root node 1 to node 4 consists of edges (1, 2), (2, 3), and (3, 4) with weights 2 + 1 + 5 = 8.
  • Query [2, 3]: The shortest path from root node 1 to node 3 consists of edges (1, 2) and (2, 3) with weights 2 + 1 = 3.
  • Query [1, 2, 3, 3]: The weight of edge (2, 3) changes from 1 to 3.
  • Query [2, 2]: The shortest path from root node 1 to node 2 is 2.
  • Query [2, 3]: The shortest path from root node 1 to node 3 consists of edges (1, 2) and (2, 3) with updated weights 2 + 3 = 5.

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • edges[i] == [ui, vi, wi]
  • 1 <= ui, vi <= n
  • 1 <= wi <= 104
  • The input is generated such that edges represents a valid tree.
  • 1 <= queries.length == q <= 105
  • queries[i].length == 2 or 4
    • queries[i] == [1, u, v, w'] or,
    • queries[i] == [2, x]
    • 1 <= u, v, x <= n
    • (u, v) is always an edge from edges.
    • 1 <= w' <= 104

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 scale of the tree (number of nodes $N$) and the number of queries ($Q$), and can we expect the queries to be processed offline, or do we need an online algorithm?
  2. Are the node labels guaranteed to be integers from $0$ to $N-1$ (or $1$ to $N$), or could they be arbitrary identifiers (like strings or sparse integers)?
  3. Since the problem states the tree has positive edge weights, is it guaranteed that a valid path always exists between any given query pair?
  4. What data types should we expect for the edge weights (e.g., standard integers, 64-bit integers to prevent overflow, or floating-point numbers)?
  5. Is the tree rooted from a specific node, or is it unrooted, meaning we are given an undirected acyclic graph where any node can act as the root?

Brute Force Solution

Approach

To find the shortest path between two points in a weighted tree using brute force, we blindly explore every single possible route that connects the starting point to the destination.

Here's how the algorithm would work step-by-step:

  1. Start at your initial location.
  2. Look at every path branching out from where you currently are.
  3. Follow every single branch to see where it leads, even if it means going in circles or heading away from your destination.
  4. Keep track of all the different paths you manage to take from the start to the finish.
  5. Add up the weights along each completed path to find its total distance.
  6. Compare the total distances of every single completed path you found.
  7. Select the path with the smallest total distance as your final answer.

Code Implementation

def shortest_path_brute_force(adjacency_list, starting_node, target_node):
    
    # We explore every branch recursively to find all possible routes to the destination
    def explore_all_routes(current_node, destination_node, current_path, current_weight):
        if current_node == destination_node:
            return [(list(current_path), current_weight)]
            
        completed_routes = []
        
        for neighbor_node, edge_weight in adjacency_list.get(current_node, []):
            if neighbor_node not in current_path:
                current_path.append(neighbor_node)
                branch_routes = explore_all_routes(
                    neighbor_node,
                    destination_node,
                    current_path,
                    current_weight + edge_weight
                )
                completed_routes.extend(branch_routes)
                current_path.pop()
                
        return completed_routes

    initial_path = [starting_node]
    all_possible_routes = explore_all_routes(starting_node, target_node, initial_path, 0)
    
    # We ensure at least one valid route exists before attempting to compare distances
    if not all_possible_routes:
        return [], float('inf')
        
    shortest_route = min(all_possible_routes, key=lambda route_tuple: route_tuple[1])
    
    return shortest_route

Big(O) Analysis

Time Complexity
O(2ⁿ) – Because a tree with n nodes has n-1 edges and contains no cycles, the brute force approach blindly explores every possible simple path from the starting node to the destination. In the worst-case scenario, from any given node, the algorithm branches out to explore all remaining unvisited nodes, generating up to 2^(n-1) potential paths. Summing the work required to traverse and evaluate each of these exponential paths leads to approximately 2ⁿ operations. Simplifying this expression by dropping constant factors yields a final time complexity of O(2ⁿ).
Space Complexity
O(N) – The brute-force exploration of every possible route relies heavily on the recursion stack to track the sequence of branches followed from the starting point to the destination. In a tree with N nodes, the maximum depth of any single branch can reach N minus 1, leading to recursive call stack frames that grow linearly with the input size. Additionally, variables are needed to track visited locations and running path weights, but the recursion stack dominates the auxiliary memory. Consequently, the total extra memory required simplifies in Big O notation to O(N).

Optimal Solution

Approach

To find the shortest path between any two locations in a tree-like network, the optimal strategy takes advantage of the unique property that trees have only one single path connecting any pair of points. Instead of wandering through every possible branch, we can simply start at the origin location and follow the single, unambiguous route straight to the destination while adding up the lengths of the connections along the way.

Here's how the algorithm would work step-by-step:

  1. Pick your starting location on the map.
  2. Trace the unique path that connects your starting location to your destination location, moving from connection to connection.
  3. As you travel along this single path, keep a running total of the distances assigned to each connection segment.
  4. Once you reach the destination, stop and look at your running total to find the final answer.

Code Implementation

def find_shortest_path_in_tree(adjacency_list, starting_node, destination_node):

    # We utilize depth-first search to traverse the tree along its single unique path.
    def traverse_tree_path(current_node, parent_node, current_distance):
        if current_node == destination_node:
            return current_distance

        # Each neighboring branch is explored to find the continuation of the path.
        for neighbor_node, edge_weight in adjacency_list[current_node]:
            if neighbor_node != parent_node:
                path_result = traverse_tree_path(neighbor_node, current_node, current_distance + edge_weight)
                if path_result is not None:
                    return path_result
        return None

    # The traversal starts from the origin location without any prior distance accumulated.
    return traverse_tree_path(starting_node, -1, 0)

Big(O) Analysis

Time Complexity
O(n) – To find the shortest path between a starting and destination location in a tree with n nodes, we traverse a single, unique path connecting them without any cycles. In the worst-case scenario, this path may span almost the entire depth or breadth of the tree, visiting up to n nodes. As we move from connection to connection, we perform a constant amount of work to sum the segment distances. This traces approximately n operations in the worst case, which simplifies to Big O of n.
Space Complexity
O(N) – To find the unique path between nodes in a tree of N nodes, the algorithm relies on a traversal strategy such as Depth-First Search or Breadth-First Search. This requires an auxiliary visited set and a parent tracking array, each of which scales linearly with N. Additionally, the recursion stack for DFS or the queue for BFS will grow up to a maximum depth or breadth of N. Therefore, the total extra memory consumed by these data structures is directly proportional to the number of nodes N, simplifying to Big O of N.

Edge Cases

Single node tree with no edges and a query asking for the distance between the node and itself
How to Handle:
Return zero as the distance since the start and end nodes are identical.
Line graph or degenerate tree resembling a linked list with maximum allowed nodes
How to Handle:
Use binary lifting or Heavy-Light Decomposition to prevent recursion depth overflow and ensure logarithmic query time.
Star graph where a single central node is connected to all other nodes
How to Handle:
Compute distances efficiently by utilizing the center node as an intermediate path point for all queries.
Very large edge weights causing integer overflow when summed along a long path
How to Handle:
Use 64-bit integer types for distance accumulators to safely handle accumulated values.
Queries asking for the shortest path between the exact same node
How to Handle:
Return zero immediately upon detecting that the source and target nodes are identical.
Disconnected graph provided instead of a valid tree structure
How to Handle:
Validate the input graph structure beforehand and throw an exception or return a sentinel value for unreachable pairs.
Massive batch of queries on a static tree structure
How to Handle:
Precompute depths and binary lifting ancestor tables during a single DFS preprocessing step to answer each query in logarithmic time.