Problem Description
Design a directed weighted graph that supports dynamic edge addition and can compute the shortest path between two nodes. The graph is initialized with n nodes and a list of edges. It supports:
- Initializing with existing edges.
- Dynamically adding a new edge.
- Querying the minimum cost between two nodes using the sum of edge costs along a valid path (return -1 if no path exists).
Key Insights
- Use an adjacency list to represent the graph efficiently for dynamic edge addition.
- Use Dijkstra’s algorithm for computing the shortest path from node1 to node2 since the graph has positive weights.
- Maintain an efficient priority queue (heap) for Dijkstra to ensure that nodes are processed in order of increasing distance.
- Since the maximum nodes (n) is small (<= 100) and there are few queries, recomputing Dijkstra for each query is acceptable.
Space and Time Complexity
Time Complexity: O(E log n) per shortestPath query where E is the number of edges at the time of the query. Space Complexity: O(n + E) since we store the graph as an adjacency list.
Solution
We represent the graph using an adjacency list, where each node maps to a list of (neighbor, edgeCost) pairs. For the shortestPath operation, we implement Dijkstra’s algorithm using a priority queue to process nodes in increasing order of their distance from the starting node. For each query, we compute the minimum distance from node1 to node2. The addEdge operation simply appends the new edge to the appropriate list in the adjacency list.