Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs

Dijkstra (Weighted Shortest Path)

O(E log V)

Greedily expand the closest unfinalized node using a min-heap keyed by distance-so-far.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstGraph BFS / DFSTop-K ElementsUnlocksBellman-FordBFS/Dijkstra on an Augmented State GraphMinimum-Cost Flow (and the assignment problem)
0%
mastery
0/16 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Min time/cost/effort on a weighted graph or grid with non-negative weights; minimax paths; max-probability paths (weights <= 1).

  1. 1Brute force

    Bellman-Ford O(VE) or enumerating paths.

  2. 2The observation

    Relaxing edges repeatedly: with non-negative weights the minimum tentative distance is final.

  3. 3Why it works

    With non-negative weights, the first time a node is popped from the min-heap its distance is final.

Reach for it when

  • +Weighted shortest path with non-negative weights — min time/cost/effort to reach a target or all nodes.
  • +Grid where moving has a cost and you want the cheapest path (min effort, min time, max-min).
  • +You'd use BFS but edges aren't uniform.

Not when

  • ×Any edge weight can be negative: nodes get finalized too earlyuse Bellman-Ford
  • ×Unweighted or all weights equaluse Plain BFS
  • ×Weights are only 0 or 1use 0-1 BFS with a deque, O(V+E)
  • ×All-pairs shortest paths on a small dense graphuse Floyd-Warshall
  • ×Limit on edges/stops: pruning on stops breaks optimalityuse Bellman-Ford k rounds, or BFS on (node, stops)

Intuition

Dijkstra finds the cheapest route from a start node to every other node when edges have non-negative weights (distances, times, costs). Plain BFS counts edges (each step = 1); Dijkstra respects weights, so a 1-edge path of weight 100 can lose to a 3-edge path of weight 5.

Read the full intuition

The idea: it's greedy with a priority queue. Keep a min-heap of "(cost so far, node)". Always expand the cheapest unfinalized node next. When you pop a node the first time, that popped cost is its final shortest distance (because every other route would have to go through something already at least as expensive — this is why non-negative weights are required). Relax its neighbours: if going through this node reaches a neighbour cheaper than known, push the better cost.

Skeleton:

Text
dist = {start: 0}; heap = [(0, start)]
while heap:
    d, u = heappop(heap)
    if d > dist[u]: continue          # stale duplicate — skip
    for v, w in adj[u]:
        if d + w < dist.get(v, INF):
            dist[v] = d + w
            heappush(heap, (d + w, v))

Key idea

Two non-obvious habits: (1) push duplicates freely and skip stale pops (if d > dist[u]: continue) instead of doing decrease-key — it's simpler and just as fast. (2) Grid variants (Path with Minimum Effort, Swim in Rising Water) replace "sum of weights" with a different cost rule (max edge, max height) but keep the exact same heap loop.

Why it costs what it costs

Time O(E log V). each edge can push once to the heap; each heap op is O(log V).

Space O(V + E). distance array, adjacency list, and the heap (up to O(E) lazy entries).

Practice

Next · Foundation

Shortest Routes I

Heap + skip stale entries; use 64-bit distances.

0/16 solved
  • Shortest Routes IFoundationFoundationCSESMedium
  • Network Delay TimeApply it · Max over shortest distances.Apply itAmazon, UberMedium
  • Path with Maximum ProbabilityOne change · Multiply probabilities, maximise.One changeMedium
  • Path With Minimum EffortTwists · Path cost is the max edge, not the sum.TwistsGoogle, UberMedium
  • Swim in Rising WaterBranches · Minimax over cell heights.BranchesGoogle, CitadelHard
  • Flight DiscountBranches · One edge can be halved.BranchesCSESMedium
  • InvestigationCombine · Count shortest paths, min and max edges among them.CombineCSESMedium
  • Number of Ways to Arrive at DestinationAdvanced · Count shortest paths mod 1e9+7.AdvancedMedium
  • Flight RoutesMastery checkMastery checkCSESMedium
  • Cheapest Flights Within K StopsAmazon, UberMedium
  • Nearest ShopsCSESHard
  • Visiting CitiesCSESHard

Pitfalls

Classic bugs

  • !No stale skip: add if d > dist[u]: continue after popping, or you reprocess nodes and TLE.
  • !Init dist[src] = 0 and everything else to infinity; reading an unreached node as 0 is a classic bug.
  • !Grid variants change how cost combines (min effort = max edge on the path). Keep the heap loop, change nd.
  • !Heap entries must be (cost, node) with cost first; flipping the tuple orders by node id.

Looks like it, isn't

  • Cheapest Flights Within K Stops needs Bellman-Ford
    Why
    The stop limit invalidates per-vertex optimality; k+1 Bellman-Ford rounds (or Dijkstra over (city, stops)).
  • Critical Cities needs Dominator Tree
    Why
    The catalog tags it dijkstra, but the question is about all routes, not shortest ones: vertices dominating n from 1. source ↗
Go deepervariants and techniques · 4 combinations · resources

Variants and techniques

  • 0-1 BFSShortest paths when edges cost 0 or 1: push 0-edges to the deque front and 1-edges to the back for O(V + E).
  • Single-source distancesStandard sum-of-weights relaxation. Network Delay Time (answer = max finalized dist).
  • Min-max (bottleneck) pathnd = max(d, edgeWeight) instead of d+w; minimize the largest edge. Path with Minimum Effort, Swim in Rising Water.
  • Max-probability pathMaximize a product of probabilities → use a max-heap and multiply. Path with Maximum Probability.
  • K-stops constraintWhen negatives or hop-limits appear, prefer Bellman-Ford. Cheapest Flights Within K Stops.

Combinations

  • Dijkstra (Weighted Shortest Path)+1D / Fibonacci-style

    number of shortest paths; min/max edges among shortest paths

    Dijkstra (Weighted Shortest Path):
    settles vertices in distance order
    1D / Fibonacci-style:
    aggregates counts/min/max edges over shortest paths

    InvestigationNumber of Ways to Arrive at Destination

  • Dijkstra (Weighted Shortest Path)+BFS/Dijkstra on an Augmented State Graph

    one discount, at most k stops, fuel, keys

    Dijkstra (Weighted Shortest Path):
    weighted shortest path
    BFS/Dijkstra on an Augmented State Graph:
    duplicates vertices per resource state

    Flight DiscountCheapest Flights Within K Stops

  • 0-1 BFS+BFS/Dijkstra on an Augmented State Graph

    minimum modifications to make a path exist

    0-1 BFS:
    0-cost and 1-cost moves
    BFS/Dijkstra on an Augmented State Graph:
    grid cell plus direction/change state

    Minimum Cost to Make at Least One Valid Path in a GridMinimum Obstacle Removal to Reach Corner

  • Dijkstra (Weighted Shortest Path)+Invariants & Parity Arguments

    grid with per-cell earliest-entry times where you may not stand still

    Dijkstra (Weighted Shortest Path):
    earliest arrival time per cell
    Invariants & Parity Arguments:
    waiting is only possible by stepping back and forth, which adds 2, so the arrival parity is fixed

    Minimum Time to Visit a Cell In a Grid

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
Union-Find (Disjoint Set)Bellman-Ford
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial