Dijkstra's Algorithm for shortest path?
Short answer: int[] Dijkstra(Dictionary<int, List<(int neighbor, int weight)>> graph, int source, int vertices) { int[] dist = new int[vertices]; for (int i = 0; i < vertices; i++) dist[i] = int.MaxValue; dist[source] = 0; var pq = new SortedSet<(int dist, int node)>(); pq.Add((0, source)); while (pq.Count > 0) { var current = pq.Min; pq.Remove(current); int u = current.node; foreach (var (v, w) in graph[u]) { if (dist[u] + w <…
Explain a bit more
dist[v]) { if (dist[v] != int.MaxValue) pq.Remove((dist[v], v)); dist[v] = dist[u] + w; pq.Add((dist[v], v)); } } } return dist; } Explanation: Uses a priority queue to pick node with min dist; relax edges.
Example code
int[] Dijkstra(Dictionary<int, List<(int neighbor, int weight)>> graph, int source, int vertices) { int[] dist = new int[vertices];
for (int i = 0; i < vertices; i++) dist[i] = int.MaxValue;
dist[source] = 0;
var pq = new SortedSet<(int dist, int node)>(); pq.Add((0, source)); while (pq.Count > 0) { var current = pq.Min; pq.Remove(current); int u = current.node;
foreach (var (v, w) in graph[u]) {
if (dist[u] + w < dist[v]) {
if (dist[v] != int.MaxValue) pq.Remove((dist[v], v)); dist[v] = dist[u] + w; pq.Add((dist[v], v)); }
}
}
return dist;
} Explanation: Uses a priority queue to pick node with min dist; relax edges.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png