MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
8.1Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals8.2Cycle Detection & Topological Sorting (Kahn's BFS & DFS)8.3Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted8.4Dynamic Programming: Overlapping Subproblems, Memoization vs Tabulation8.5Classic DP Master Patterns: 0/1 Knapsack, Coin Change & LCS
HomeTutorialsData Structures & AlgorithmsShortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted
Dynamic Programming: Overlapping Subproblems, Memoization vs Tabulation

Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Finding the shortest path between nodes in a network is one of the foundational problems of computer science. It powers GPS navigation systems (Google Maps, Apple Maps), internet packet routing (OSPF, IS-IS protocols), and robotic motion planning.


1. Shortest Path Algorithms Overview

The choice of algorithm depends on edge weights:

Graph CharacteristicOptimal AlgorithmTime ComplexityNotes
Unweighted Graph (all weights = 1)BFS$O(V + E)$Fastest; queue guarantees minimal hops
Non-Negative Weights ($w \ge 0$)Dijkstra's Algorithm$O((V + E) \log V)$Greedy; uses Min-Priority Queue
Negative Weights AllowedBellman-Ford Algorithm$O(V \times E)$Slower; can detect negative weight cycles
All-Pairs Shortest PathFloyd-Warshall$O(V^3)$Dynamic programming matrix approach
Critical Constraint: Dijkstra's algorithm CANNOT handle graphs with negative edge weights! A negative weight violates the greedy assumption that once a node is finalized from the priority queue, its shortest distance cannot be improved.

2. Dijkstra's Algorithm Mechanics

Dijkstra uses a Greedy Strategy with a Min-Heap (Priority Queue):

1Dijkstra Core Mechanism:
21. Set dist[start] = 0; dist[v] = infinity for all other vertices v.
32. Push (0, start) into Min-Heap (storing (distance, node)).
43. While Min-Heap is not empty:
5 (current_dist, u) = heap.pop()
6 if current_dist > dist[u]:
7 continue # Outdated duplicate entry in heap; skip!
8 for each neighbor (v, weight) of u:
9 new_dist = dist[u] + weight
10 if new_dist < dist[v]:
11 dist[v] = new_dist
12 heap.push((new_dist, v))
13 parent[v] = u # To reconstruct the path

3. Step-by-Step Trace Table

Consider a weighted directed graph with 4 nodes:

  • $(0 \to 1, w=4)$
  • $(0 \to 2, w=1)$
  • $(2 \to 1, w=2)$
  • $(1 \to 3, w=1)$
  • $(2 \to 3, w=5)$

Find shortest path from Node 0 to all nodes:

StepPop (dist, node)Action / Edge RelaxationsMin-Heap ContentsDistances [0, 1, 2, 3]
Init-Start node 0[(0, 0)][0, inf, inf, inf]
1(0, 0)Relax $0 \to 1$ ($0+4=4$), $0 \to 2$ ($0+1=1$)[(1, 2), (4, 1)][0, 4, 1, inf]
2(1, 2)Relax $2 \to 1$ ($1+2=3 < 4$! Better!), $2 \to 3$ ($1+5=6$)[(3, 1), (4, 1), (6, 3)][0, 3, 1, 6]
3(3, 1)Relax $1 \to 3$ ($3+1=4 < 6$! Better!)[(4, 1), (4, 3), (6, 3)][0, 3, 1, 4]
4(4, 1)Skipped! $4 > \text{dist}[1] (3)$ (Stale entry)[(4, 3), (6, 3)][0, 3, 1, 4]
5(4, 3)Finalized node 3. No outgoing edges.[(6, 3)][0, 3, 1, 4]
6(6, 3)Skipped! $6 > \text{dist}[3] (4)$[][0, 3, 1, 4]

Final Shortest Distances: dist[0]=0, dist[1]=3, dist[2]=1, dist[3]=4. Shortest path to 3: $0 \to 2 \to 1 \to 3$ with total cost $1 + 2 + 1 = 4$.


4. Dual-Language Implementation

Python 3 Implementation

1import heapq
2from typing import List, Tuple, Dict
3 
4def dijkstra(num_nodes: int, edges: List[Tuple[int, int, int]], start: int) -> Tuple[List[float], List[int]]:
5 # edges: list of tuples (u, v, weight)
6 # Returns (distances, parent_array)
7 adj: Dict[int, List[Tuple[int, int]]] = {i: [] for i in range(num_nodes)}
8 for u, v, w in edges:
9 adj[u].append((v, w))
10 
11 distances = [float('inf')] * num_nodes
12 parent = [-1] * num_nodes
13 distances[start] = 0
14 
15 # Min-Heap stores (distance_from_start, current_node)
16 min_heap: List[Tuple[float, int]] = [(0, start)]
17 
18 while min_heap:
19 curr_dist, u = heapq.heappop(min_heap)
20 
21 # Skip stale entries
22 if curr_dist > distances[u]:
23 continue
24 
25 for v, weight in adj[u]:
26 new_dist = curr_dist + weight
27 if new_dist < distances[v]:
28 distances[v] = new_dist
29 parent[v] = u
30 heapq.heappush(min_heap, (new_dist, v))
31 
32 return distances, parent
33 
34def reconstruct_path(parent: List[int], target: int) -> List[int]:
35 path = []
36 curr = target
37 while curr != -1:
38 path.append(curr)
39 curr = parent[curr]
40 return path[::-1]
41 
42# Example Test
43if __name__ == "__main__":
44 edges = [
45 (0, 1, 4), (0, 2, 1),
46 (2, 1, 2), (1, 3, 1),
47 (2, 3, 5)
48 ]
49 dists, parents = dijkstra(4, edges, 0)
50 print("Shortest Distances:", dists) # [0, 3, 1, 4]
51 print("Path to Node 3:", reconstruct_path(parents, 3)) # [0, 2, 1, 3]

Modern JavaScript (Node.js) Implementation

1class MinPriorityQueue {
2 constructor() {
3 this.heap = [];
4 }
5 
6 push(element) {
7 this.heap.push(element);
8 this._bubbleUp(this.heap.length - 1);
9 }
10 
11 pop() {
12 if (this.heap.length === 0) return null;
13 const min = this.heap[0];
14 const end = this.heap.pop();
15 if (this.heap.length > 0) {
16 this.heap[0] = end;
17 this._sinkDown(0);
18 }
19 return min;
20 }
21 
22 isEmpty() {
23 return this.heap.length === 0;
24 }
25 
26 _bubbleUp(idx) {
27 const el = this.heap[idx];
28 while (idx > 0) {
29 const parentIdx = Math.floor((idx - 1) / 2);
30 const parent = this.heap[parentIdx];
31 if (el.cost >= parent.cost) break;
32 this.heap[idx] = parent;
33 idx = parentIdx;
34 }
35 this.heap[idx] = el;
36 }
37 
38 _sinkDown(idx) {
39 const length = this.heap.length;
40 const el = this.heap[idx];
41 while (true) {
42 let left = 2 * idx + 1;
43 let right = 2 * idx + 2;
44 let swap = null;
45 
46 if (left < length && this.heap[left].cost < el.cost) {
47 swap = left;
48 }
49 if (
50 right < length &&
51 (swap === null ? this.heap[right].cost < el.cost : this.heap[right].cost < this.heap[left].cost)
52 ) {
53 swap = right;
54 }
55 
56 if (swap === null) break;
57 this.heap[idx] = this.heap[swap];
58 idx = swap;
59 }
60 this.heap[idx] = el;
61 }
62}
63 
64function dijkstra(numNodes, edges, start) {
65 const adj = Array.from({ length: numNodes }, () => []);
66 edges.forEach(([u, v, w]) => adj[u].push({ to: v, weight: w }));
67 
68 const distances = new Array(numNodes).fill(Infinity);
69 distances[start] = 0;
70 
71 const pq = new MinPriorityQueue();
72 pq.push({ node: start, cost: 0 });
73 
74 while (!pq.isEmpty()) {
75 const { node: u, cost: currDist } = pq.pop();
76 
77 if (currDist > distances[u]) continue;
78 
79 for (const { to: v, weight } of adj[u]) {
80 const newDist = currDist + weight;
81 if (newDist < distances[v]) {
82 distances[v] = newDist;
83 pq.push({ node: v, cost: newDist });
84 }
85 }
86 }
87 
88 return distances;
89}
90 
91// Example Test
92const edges = [
93 [0, 1, 4], [0, 2, 1],
94 [2, 1, 2], [1, 3, 1],
95 [2, 3, 5]
96];
97console.log("Dijkstra Distances:", dijkstra(4, edges, 0)); // [0, 3, 1, 4]

5. Complexity & Optimality Analysis

  • Time Complexity: $O((V + E) \log V)$
  • Each vertex is pushed to the heap at least once, and edge relaxations trigger heap pushes ($E$ pushes total).
  • Heap insertion/extraction takes $O(\log V)$.
  • Total time: $O(E \log V + V \log V) = O((V + E) \log V)$.
  • Space Complexity: $O(V + E)$
  • Distance array: $O(V)$.
  • Adjacency list: $O(V + E)$.
  • Heap entries: $O(E)$ worst case.

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Why does Dijkstra's algorithm fail when applied to graphs containing negative edge weights?
Question 2
What is the time complexity of Dijkstra's algorithm implemented with a binary min-heap for a graph with $V$ vertices and $E$ edges?
Question 3
If all edge weights in a directed weighted graph are equal to 1, which algorithm should be preferred over Dijkstra for finding shortest paths?
Question 4
What is the purpose of the condition if curr_dist > distances[u]: continue in Dijkstra's heap loop?
Question 5
Which data structure allows the theoretical optimal time complexity of $O(E + V \log V)$ for Dijkstra's algorithm?

Next Lesson

Dynamic Programming: Overlapping Subproblems, Memoization vs Tabulation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Cycle Detection & Topological Sorting (Kahn's BFS & DFS)Dynamic Programming: Overlapping Subproblems, Memoization vs Tabulation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext