#2642

Design Graph With Shortest Path Calculator

Hard
Graph TheoryDesignHeap (Priority Queue)Shortest PathGraph TraversalPriority QueueDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O((E + V) log V)
Space
O(1)
O(V)
💡

Intuition

Time O((E + V) log V)Space O(V)

Using Dijkstra's algorithm allows us to efficiently find the shortest path in a weighted graph. It systematically explores the nearest nodes first, ensuring we find the minimum cost path without exploring every possible route.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a priority queue (min-heap) and a distance array to track the minimum cost to reach each node.
  2. 2Step 2: Start from node1, add it to the priority queue with a cost of 0.
  3. 3Step 3: While the priority queue is not empty, extract the node with the smallest cost, update its neighbors, and push them into the queue if a shorter path is found.
  4. 4Step 4: If we reach node2, return the cost; if the queue is empty and node2 is not reached, return -1.
solution.py29 lines
1import heapq
2class Graph:
3    def __init__(self, n, edges):
4        self.graph = {}
5        for u, v, cost in edges:
6            if u not in self.graph:
7                self.graph[u] = []
8            self.graph[u].append((v, cost))
9
10    def addEdge(self, edge):
11        u, v, cost = edge
12        if u not in self.graph:
13            self.graph[u] = []
14        self.graph[u].append((v, cost))
15
16    def shortestPath(self, node1, node2):
17        pq = [(0, node1)]
18        distances = {i: float('inf') for i in range(len(self.graph))}
19        distances[node1] = 0
20        while pq:
21            current_cost, current_node = heapq.heappop(pq)
22            if current_node == node2:
23                return current_cost
24            for neighbor, cost in self.graph.get(current_node, []):
25                new_cost = current_cost + cost
26                if new_cost < distances[neighbor]:
27                    distances[neighbor] = new_cost
28                    heapq.heappush(pq, (new_cost, neighbor))
29        return -1

Complexity note: The time complexity is derived from the priority queue operations, where E is the number of edges and V is the number of vertices. Each edge is processed once, and each vertex is added to the queue at most once.

  • 1Dijkstra's algorithm is efficient for finding the shortest path in weighted graphs.
  • 2Understanding how to use priority queues can significantly optimize pathfinding problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.