Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Dijkstra's Algorithm Single Source Shortest Path in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dijkstra Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Dijkstra's Algorithm on a Simple Graph
What is the output distances object after running Dijkstra's algorithm from node 'A' on the given graph?
DSA Javascript
const graph = {
  A: { B: 4, C: 1 },
  B: { A: 4, C: 2, D: 5 },
  C: { A: 1, B: 2, D: 8, E: 10 },
  D: { B: 5, C: 8, E: 2, Z: 6 },
  E: { C: 10, D: 2, Z: 3 },
  Z: { D: 6, E: 3 }
};

function dijkstra(graph, start) {
  const distances = {};
  const visited = new Set();
  const nodes = Object.keys(graph);

  nodes.forEach(node => distances[node] = Infinity);
  distances[start] = 0;

  while (visited.size !== nodes.length) {
    let closestNode = null;
    let shortestDistance = Infinity;

    nodes.forEach(node => {
      if (!visited.has(node) && distances[node] < shortestDistance) {
        shortestDistance = distances[node];
        closestNode = node;
      }
    });

    if (closestNode === null) break;

    visited.add(closestNode);

    const neighbors = graph[closestNode];
    for (const neighbor in neighbors) {
      const newDist = distances[closestNode] + neighbors[neighbor];
      if (newDist < distances[neighbor]) {
        distances[neighbor] = newDist;
      }
    }
  }

  return distances;
}

const result = dijkstra(graph, 'A');
console.log(result);
A{"A":0,"B":3,"C":1,"D":8,"E":10,"Z":13}
B{"A":0,"B":4,"C":1,"D":7,"E":9,"Z":12}
C{"A":0,"B":3,"C":1,"D":7,"E":9,"Z":12}
D{"A":0,"B":4,"C":1,"D":8,"E":10,"Z":13}
Attempts:
2 left
💡 Hint
Trace the shortest paths step by step from node 'A' updating distances.
🧠 Conceptual
intermediate
1:00remaining
Understanding Priority in Dijkstra's Algorithm
In Dijkstra's algorithm, which data structure is best suited to efficiently select the next node with the smallest tentative distance?
APriority Queue (Min-Heap)
BQueue
CStack
DHash Table
Attempts:
2 left
💡 Hint
Think about how to always pick the node with the smallest distance quickly.
🔧 Debug
advanced
1:30remaining
Identify the Bug in Dijkstra's Algorithm Implementation
What error will the following code produce when running Dijkstra's algorithm on a graph with disconnected nodes?
DSA Javascript
function dijkstra(graph, start) {
  const distances = {};
  const visited = new Set();
  const nodes = Object.keys(graph);

  nodes.forEach(node => distances[node] = Infinity);
  distances[start] = 0;

  while (visited.size !== nodes.length) {
    let closestNode = null;
    let shortestDistance = Infinity;

    nodes.forEach(node => {
      if (!visited.has(node) && distances[node] < shortestDistance) {
        shortestDistance = distances[node];
        closestNode = node;
      }
    });

    if (closestNode === null) break;

    visited.add(closestNode);

    const neighbors = graph[closestNode];
    for (const neighbor in neighbors) {
      const newDist = distances[closestNode] + neighbors[neighbor];
      if (newDist < distances[neighbor]) {
        distances[neighbor] = newDist;
      }
    }
  }

  return distances;
}
AInfinite loop because closestNode never becomes null
BNo error, runs correctly
CSyntaxError due to missing semicolon
DTypeError: Cannot read property of undefined when accessing neighbors
Attempts:
2 left
💡 Hint
Consider what happens when closestNode is null.
🚀 Application
advanced
1:30remaining
Applying Dijkstra's Algorithm to Find Shortest Path Distance
Given the graph below, what is the shortest distance from node 'X' to node 'Y' using Dijkstra's algorithm? Graph edges with weights: X -> A (2), X -> B (5), A -> B (1), A -> Y (7), B -> Y (2)
A7
B5
C9
D10
Attempts:
2 left
💡 Hint
Consider all paths from X to Y and sum their weights.
❓ Predict Output
expert
2:00remaining
Output of Dijkstra's Algorithm with Negative Edge Weight
What will be the output or error when running Dijkstra's algorithm on the following graph with a negative edge weight?
DSA Javascript
const graph = {
  A: { B: 1, C: 4 },
  B: { C: -3, D: 2 },
  C: { D: 3 },
  D: {}
};

function dijkstra(graph, start) {
  const distances = {};
  const visited = new Set();
  const nodes = Object.keys(graph);

  nodes.forEach(node => distances[node] = Infinity);
  distances[start] = 0;

  while (visited.size !== nodes.length) {
    let closestNode = null;
    let shortestDistance = Infinity;

    nodes.forEach(node => {
      if (!visited.has(node) && distances[node] < shortestDistance) {
        shortestDistance = distances[node];
        closestNode = node;
      }
    });

    if (closestNode === null) break;

    visited.add(closestNode);

    const neighbors = graph[closestNode];
    for (const neighbor in neighbors) {
      const newDist = distances[closestNode] + neighbors[neighbor];
      if (newDist < distances[neighbor]) {
        distances[neighbor] = newDist;
      }
    }
  }

  return distances;
}

const result = dijkstra(graph, 'A');
console.log(result);
A{"A":0,"B":1,"C":4,"D":7}
B{"A":0,"B":1,"C":-2,"D":0}
C{"A":0,"B":1,"C":-2,"D":1}
DAlgorithm produces incorrect distances due to negative edge weight
Attempts:
2 left
💡 Hint
Dijkstra's algorithm does not work correctly with negative edge weights.

Practice

(1/5)
1. What is the main purpose of Dijkstra's Algorithm in graph theory?
easy
A. To sort vertices in topological order
B. To find the maximum flow in a network
C. To detect cycles in a graph
D. To find the shortest path from a single source to all other vertices

Solution

  1. Step 1: Understand the algorithm's goal

    Dijkstra's Algorithm is designed to find the shortest paths from one starting point (source) to all other points in a graph with non-negative edge weights.
  2. Step 2: Compare with other graph algorithms

    Other algorithms like max flow or cycle detection serve different purposes, so they do not match Dijkstra's goal.
  3. Final Answer:

    To find the shortest path from a single source to all other vertices -> Option D
  4. Quick Check:

    Shortest path from one source = To find the shortest path from a single source to all other vertices [OK]
Hint: Dijkstra finds shortest paths from one start point [OK]
Common Mistakes:
  • Confusing Dijkstra with max flow algorithms
  • Thinking it detects cycles
  • Assuming it sorts vertices
2. Which of the following is the correct way to initialize the distance array in Dijkstra's Algorithm in JavaScript?
easy
A. const dist = new Array(n).fill(Infinity); dist[source] = 0;
B. const dist = Array(n).fill(0); dist[source] = Infinity;
C. const dist = new Array(n).fill(null); dist[source] = 0;
D. const dist = new Array(n).fill(-1); dist[source] = 0;

Solution

  1. Step 1: Understand distance initialization

    Distances to all nodes except the source should start as Infinity to represent unknown paths, and the source distance is 0.
  2. Step 2: Check each option

    const dist = new Array(n).fill(Infinity); dist[source] = 0; correctly sets all distances to Infinity and source to 0. Others either set wrong initial values or invert source distance.
  3. Final Answer:

    const dist = new Array(n).fill(Infinity); dist[source] = 0; -> Option A
  4. Quick Check:

    Distance array starts with Infinity except source = const dist = new Array(n).fill(Infinity); dist[source] = 0; [OK]
Hint: Start distances as Infinity, source as 0 [OK]
Common Mistakes:
  • Setting source distance to Infinity
  • Using 0 for all distances initially
  • Using null or -1 incorrectly
3. Consider the following JavaScript code snippet implementing part of Dijkstra's Algorithm. What will be the output of the distance array after running this code?
const graph = {
  0: [{node:1, weight:4}, {node:2, weight:1}],
  1: [{node:3, weight:1}],
  2: [{node:1, weight:2}, {node:3, weight:5}],
  3: []
};
const dist = [0, Infinity, Infinity, Infinity];
const visited = new Set();

function dijkstra() {
  while (visited.size < 4) {
    let u = -1;
    let minDist = Infinity;
    for (let i = 0; i < 4; i++) {
      if (!visited.has(i) && dist[i] < minDist) {
        minDist = dist[i];
        u = i;
      }
    }
    visited.add(u);
    for (const neighbor of graph[u]) {
      if (dist[u] + neighbor.weight < dist[neighbor.node]) {
        dist[neighbor.node] = dist[u] + neighbor.weight;
      }
    }
  }
}
dijkstra();
console.log(dist);
medium
A. [0, 4, 1, 6]
B. [0, 3, 1, 4]
C. [0, 2, 1, 3]
D. [0, 5, 1, 7]

Solution

  1. Step 1: Trace initial distances and first iteration

    Start dist = [0, Infinity, Infinity, Infinity]. Pick node 0 (dist=0). Update neighbors: node 1 = 4, node 2 = 1.
  2. Step 2: Next iterations and updates

    Pick node 2 (dist=1). Update node 1: min(4, 1+2=3) = 3; node 3: min(Infinity, 1+5=6) = 6. Pick node 1 (dist=3). Update node 3: min(6, 3+1=4) = 4. Pick node 3 (dist=4). No neighbors.
  3. Final Answer:

    [0, 3, 1, 4] -> Option B
  4. Quick Check:

    Distances after updates = [0, 3, 1, 4] [OK]
Hint: Pick unvisited node with smallest dist, update neighbors [OK]
Common Mistakes:
  • Not updating distances correctly
  • Choosing wrong next node
  • Ignoring neighbor updates
4. The following code snippet is intended to implement Dijkstra's Algorithm but contains a bug. What is the bug?
const dist = new Array(n).fill(Infinity);
dist[source] = 0;
const visited = new Set();

while (visited.size < n) {
  let u = -1;
  let minDist = Infinity;
  for (let i = 0; i < n; i++) {
    if (dist[i] < minDist) {
      minDist = dist[i];
      u = i;
    }
  }
  visited.add(u);
  for (const neighbor of graph[u]) {
    if (dist[u] + neighbor.weight < dist[neighbor.node]) {
      dist[neighbor.node] = dist[u] + neighbor.weight;
    }
  }
}
medium
A. The visited set is not updated inside the loop
B. The distance array is not initialized correctly
C. The code does not check if node i is already visited before selecting u
D. The neighbor weights are not added to dist[u]

Solution

  1. Step 1: Analyze node selection loop

    The loop selects node u with smallest dist[i] but does not check if i is already visited, so it may pick visited nodes again.
  2. Step 2: Understand impact of missing visited check

    Without skipping visited nodes, the algorithm can loop incorrectly or update distances wrongly, breaking correctness.
  3. Final Answer:

    The code does not check if node i is already visited before selecting u -> Option C
  4. Quick Check:

    Must skip visited nodes when picking u = The code does not check if node i is already visited before selecting u [OK]
Hint: Always skip visited nodes when choosing next node [OK]
Common Mistakes:
  • Forgetting to check visited nodes in selection
  • Incorrect distance initialization
  • Not updating visited set
5. You have a weighted graph with 5 nodes (0 to 4). The edges are:
  • 0 -> 1 (2)
  • 0 -> 2 (4)
  • 1 -> 2 (1)
  • 1 -> 3 (7)
  • 2 -> 4 (3)
  • 3 -> 4 (1)

Using Dijkstra's Algorithm from source node 0, what is the shortest distance to node 4?
hard
A. 6
B. 7
C. 8
D. 5

Solution

  1. Step 1: Trace shortest paths from node 0

    Start dist: 0=0, others=Infinity. From 0: dist[1]=2, dist[2]=4.
  2. Step 2: Update distances via neighbors

    From 1: dist[2]=min(4,2+1=3)=3, dist[3]=2+7=9. From 2: dist[4]=3+3=6. From 3: dist[4]=min(6,9+1=10)=6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Shortest distance to node 4 = 6 [OK]
Hint: Check all paths, pick minimum sum of weights [OK]
Common Mistakes:
  • Ignoring shorter path through node 2
  • Adding wrong edge weights
  • Not updating distances properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard