Dijkstra's algorithm

Asked atAtlassianGoogleLinkedinMicrosoftUKG
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a weighted, undirected graph of V vertices, numbered from 0 to V-1, and an 2D vector/array which represents the edges:

Each entry in** edges[i] is of the form [u, v, weight]**, where:

  • **u, v **→ represents the vertex having undirected edge between them
  • weight → the weight of the edge between u and v

Given a source node S. Find the shortest distance of all the vertex from the source vertex S. Return a list of integers denoting **shortest distance **between each node and source vertex S. If a vertex is not reachable from source then its distance will be 109.

Input: V = 2, edges = [[0,1,9]] , S=0 Output: [0, 9] **Explanation: ** The shortest distance from node 0(source) to node 0 is 0 and the shortest distance from node 0 to node 1 is 9.

Input: V = 3, edges = [[0, 1, 1], [0, 2, 6], [1, 2, 3]] , S=2 Output: [4, 3, 0] **Explanation: ** For node 0, the shortest path is 2->1->0 (distance=4) For node 1, the shortest path is 2->1 (distance=3)

Input: V=4, edges = [[0,1,1],[0,3,2],[1,2,4],[2,3,3]] , S=0

  • 1 ≤ V ≤ 10000
  • 0 ≤ edges[i][j] ≤ 10000
  • 1 ≤ edges.size() ≤ [ (V*(V - 1)) / 2 ]
  • 0 ≤ S < V

cpp

class Solution{
public:
    vector<int> dijkstra(int V, vector<vector<int>> edges, int S) {

    }
};

java

class Solution
{
    public  int[] dijkstra(int V, ArrayList<ArrayList<Integer>> edges, int S)
    {
       
    }
}

python

class Solution:
    def dijkstra(self, V, edges, S):

javascript

class Solution {
    dijkstra(V, edges, S) {
  
    }
}

csharp

public class Solution
{
    public int[] Dijkstra(int V, List<List<int>> edges, int S)
    {
  
    }
}

go

func dijkstra(V int, edges [][]int, S int) []int {
	
}
Stuck? Show a way to structure it+
  1. 01Build an adjacency list and initialize every distance to infinity except the source.
  2. 02Use a min-heap of [distance, vertex] pairs, beginning with [0, source].
  3. 03Ignore stale heap entries and relax every outgoing edge from the current vertex.
  4. 04Return the finalized distances, mapping unreachable vertices to the required sentinel.

Reference answer

Then expect these follow-ups

  • What changes if some edges can have negative weights?

    Tests: algorithm selection

  • How would you reconstruct one shortest path, not just its distance?

    Tests: path reconstruction

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question