← All Exercises

Dijkstra Shortest Path with a Binary Heap

advancedjavascript~25min

Background

Dijkstra's algorithm powers routing engines, network latency maps, and game pathfinding on graphs with non-negative weights.

Problem

Given a weighted directed graph as an adjacency object, a start node, and a target node, return the cheapest path cost or -1 when the target is unreachable.

Input

An object mapping each node to an object of neighbour-to-weight entries, plus start and target node names.

Output

A non-negative number for the shortest distance, or -1 if no path exists.

Sample tests

Sample 1

Input: graph = {A:{B:1,C:4},B:{C:2},C:{}}, start = "A", target = "C"
Expected: 3

Sample 2

Input: graph = {A:{B:5},B:{C:1},C:{}}, start = "A", target = "C"
Expected: 6

Sample 3

Input: graph = {A:{B:2},B:{}}, start = "A", target = "C"
Expected: -1

Your solution

Learning objective

Combine a binary heap with edge relaxation and skip stale entries to achieve O((V + E) log V).