CodeMosa

Master LeetCode Patterns

Dijkstra's Algorithm

Single-source shortest paths on non-negative weighted graphs using a priority queue.

Time: O((V+E) log V)
Space: O(V)

What is Dijkstra's Algorithm?

#
Definition: Compute shortest paths from a single source on graphs with non‑negative weights using a min‑priority queue.

Core Idea

#

Maintain tentative distances and relax edges by always expanding the node with the smallest current distance (min-heap).

When to Use

#

Use on graphs with non-negative weights for shortest paths; prefer 0-1 BFS for 0/1 weights or Bellman-Ford if negatives exist.

How Dijkstra's Algorithm works

#

Initialize distances to ∞, push (0, src) to a min-heap, pop best and relax neighbors; skip if popped distance is stale.

  • Non-negative weights
  • Shortest path from a source
  • Road/map routing

Dijkstra's Algorithm vs alternatives

#

Use this pattern when use on graphs with non-negative weights for shortest paths; prefer 0-1 bfs for 0/1 weights or bellman-ford if negatives exist.

General Recognition Cues

#
General indicators that this pattern might be applicable
  • Non-negative weights
  • Shortest path from a source
  • Road/map routing
#
Curated practice sets for this pattern

Code Templates

#
Initialize distances to ∞, push (0, src) to a min-heap, pop best and relax neighbors; skip if popped distance is stale.
import heapq
def dijkstra(n, adj, src):
    dist=[float('inf')]*n; dist[src]=0
    pq=[(0,src)]
    while pq:
        d,u=heapq.heappop(pq)
        if d!=dist[u]: continue
        for v,w in adj[u]:
            nd=d+w
            if nd<dist[v]: dist[v]=nd; heapq.heappush(pq,(nd,v))
    return dist

Pattern Variants & Approaches

#
Different methodologies and implementations for this pattern
1

Heap-based Dijkstra

#

Typical implementation with a min-priority queue.

When to Use This Variant
  • Non-negative weights
Use Case
Sparse graphs
Advantages
  • O((V+E) log V)
  • Efficient in practice
Implementation
import heapq
def dijkstra(n, adj, src):
    dist=[float('inf')]*n; dist[src]=0
    pq=[(0,src)]
    while pq:
        d,u=heapq.heappop(pq)
        if d!=dist[u]: continue
        for v,w in adj[u]:
            nd=d+w
            if nd<dist[v]: dist[v]=nd; heapq.heappush(pq,(nd,v))
    return dist
2

When Dijkstra vs BFS vs 0-1 BFS

#

Pick by weight type: unweighted→BFS, {0,1}→0-1 BFS, non-negative→Dijkstra

When to Use This Variant
  • Unweighted
  • Binary weights
  • Non-negative weights
Use Case
Choosing the right shortest-path approach
Advantages
  • Avoids overkill
  • Linear-time options when possible
  • Correctness by preconditions
Implementation
import heapq
def dijkstra(n, adj, src):
    dist=[float('inf')]*n; dist[src]=0
    pq=[(0,src)]
    while pq:
        d,u=heapq.heappop(pq)
        if d!=dist[u]: continue
        for v,w in adj[u]:
            nd=d+w
            if nd<dist[v]: dist[v]=nd; heapq.heappush(pq,(nd,v))
    return dist
3

Negative Weights → Bellman-Ford

#

Relax edges V-1 times; detect negative cycles by an extra pass

When to Use This Variant
  • Negative edge weights
  • Need cycle detection
Use Case
Graphs with negative edges or to detect negative cycles
Advantages
  • Handles negatives
  • Simple
Implementation
def bellman_ford(n, edges, src):
    INF=10**18; dist=[INF]*n; dist[src]=0
    for _ in range(n-1):
        changed=False
        for u,v,w in edges:
            if dist[u]+w<dist[v]: dist[v]=dist[u]+w; changed=True
        if not changed: break
    # Optional: detect negative cycle
    for u,v,w in edges:
        if dist[u]+w<dist[v]: return None  # negative cycle
    return dist

Common Pitfalls

#
Watch out for these common mistakes
  • Using Dijkstra with negative edges
  • Not skipping stale heap entries
  • Not using min-priority queue
#

Example Problems

#
Classic LeetCode problems using this pattern

Complexity Analysis

#
Time Complexity
O((V+E) log V)

Each edge can relax once; heap ops cost log V.

Space Complexity
O(V)

Distance array + heap.

Ready to test your knowledge?

Test your pattern recognition with interactive questions