#3123

Find Edges in Shortest Paths

Hard
Depth-First SearchBreadth-First SearchGraph TheoryHeap (Priority Queue)Shortest PathDijkstra's AlgorithmGraph TraversalPriority Queue
LeetCode ↗

Approaches

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

Intuition

Time O((n + m) log n)Space O(n)

We can use Dijkstra's algorithm to find the shortest path from node 0 to all other nodes and from node n-1 to all other nodes. This allows us to efficiently determine if an edge is part of any shortest path.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use Dijkstra's algorithm to find the shortest distance from node 0 to all other nodes.
  2. 2Step 2: Use Dijkstra's algorithm again to find the shortest distance from node n-1 to all other nodes.
  3. 3Step 3: For each edge, check if the sum of the distances from node 0 to the start of the edge, the weight of the edge, and the distance from the end of the edge to node n-1 equals the shortest distance from node 0 to n-1.
solution.py32 lines
1import heapq
2from collections import defaultdict
3
4def find_edges_in_shortest_paths(n, edges):
5    graph = defaultdict(list)
6    for a, b, w in edges:
7        graph[a].append((b, w))
8        graph[b].append((a, w))
9
10    def dijkstra(start):
11        distances = [float('inf')] * n
12        distances[start] = 0
13        pq = [(0, start)]
14        while pq:
15            curr_dist, node = heapq.heappop(pq)
16            if curr_dist > distances[node]: continue
17            for neighbor, weight in graph[node]:
18                distance = curr_dist + weight
19                if distance < distances[neighbor]:
20                    distances[neighbor] = distance
21                    heapq.heappush(pq, (distance, neighbor))
22        return distances
23
24    dist_from_start = dijkstra(0)
25    dist_from_end = dijkstra(n - 1)
26    min_distance = dist_from_start[n - 1]
27    answer = [False] * len(edges)
28    for i, (a, b, w) in enumerate(edges):
29        if dist_from_start[a] + w + dist_from_end[b] == min_distance or \
30           dist_from_start[b] + w + dist_from_end[a] == min_distance:
31            answer[i] = True
32    return answer

Complexity note: Dijkstra's algorithm runs in O((n + m) log n) time due to the priority queue operations, making it efficient for sparse graphs.

  • 1Using Dijkstra's algorithm allows us to efficiently find shortest paths in weighted graphs.
  • 2Checking both directions (from start and end) helps in determining if an edge is part of the shortest path.

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