Shortest Path (Dijkstra) - Problem

Given a weighted graph represented as an adjacency list and a source vertex, implement Dijkstra's algorithm to find the shortest path from the source to all other vertices.

The graph is represented as a list of edges where each edge is [from, to, weight]. Return an array where result[i] is the shortest distance from the source to vertex i. If a vertex is unreachable, use -1.

Note: All edge weights are non-negative integers. Vertices are numbered from 0 to n-1.

Input & Output

Example 1 — Basic Graph
$ Input: n = 4, edges = [[0,1,4],[0,2,2],[1,3,3],[2,3,1]], source = 0
Output: [0,4,2,3]
💡 Note: From vertex 0: distance to 0 is 0, to 1 is 4 (direct), to 2 is 2 (direct), to 3 is 3 (via 2→3 path costs 2+1=3, better than 1→3 path costs 4+3=7)
Example 2 — Disconnected Vertex
$ Input: n = 3, edges = [[0,1,5]], source = 0
Output: [0,5,-1]
💡 Note: From vertex 0: distance to 0 is 0, to 1 is 5 (direct edge), to 2 is -1 (unreachable since no path exists)
Example 3 — Single Vertex
$ Input: n = 1, edges = [], source = 0
Output: [0]
💡 Note: Only one vertex exists, distance from vertex 0 to itself is 0

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ n × (n-1)
  • 0 ≤ source < n
  • 0 ≤ weight ≤ 100

Visualization

Tap to expand
INPUT GRAPHDIJKSTRA STEPSFINAL RESULT01234231Source: vertex 0Find shortest pathsto all other vertices1Initialize: dist[0]=0, others=∞2Process vertex 0, update neighbors3Process vertex 2 (dist=2)4Process vertex 3 (dist=3)Priority QueueAlways extract minimumdistance vertex firstDistance Array[0, 4, 2, 3]• Vertex 0: distance 0• Vertex 1: distance 4 (0→1)• Vertex 2: distance 2 (0→2)• Vertex 3: distance 3 (0→2→3)Optimal paths found!Key Insight:Processing vertices in order of increasing distance guarantees that when we finalizea vertex, we have found its true shortest path and never need to reconsider it.TutorialsPoint - Shortest Path (Dijkstra) | Priority Queue Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
34.5K Views
High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen