0
0
DSA Typescriptprogramming~20 mins

Shortest Path in DAG Using Topological Order in DSA Typescript - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
DAG Shortest Path Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of shortest path distances after topological order processing
Given the following TypeScript code that finds shortest paths in a Directed Acyclic Graph (DAG) using topological order, what is the printed output array representing shortest distances from source node 0?
DSA Typescript
type Edge = [number, number, number];

function shortestPathDAG(n: number, edges: Edge[], src: number): number[] {
  const graph: Map<number, [number, number][]> = new Map();
  for (let i = 0; i < n; i++) graph.set(i, []);
  for (const [u, v, w] of edges) {
    graph.get(u)!.push([v, w]);
  }

  const visited = new Array(n).fill(false);
  const stack: number[] = [];

  function dfs(node: number) {
    visited[node] = true;
    for (const [nbr] of graph.get(node)!) {
      if (!visited[nbr]) dfs(nbr);
    }
    stack.push(node);
  }

  for (let i = 0; i < n; i++) {
    if (!visited[i]) dfs(i);
  }

  const dist = new Array(n).fill(Infinity);
  dist[src] = 0;

  while (stack.length) {
    const node = stack.pop()!;
    if (dist[node] !== Infinity) {
      for (const [nbr, w] of graph.get(node)!) {
        if (dist[node] + w < dist[nbr]) {
          dist[nbr] = dist[node] + w;
        }
      }
    }
  }

  return dist;
}

const n = 6;
const edges: Edge[] = [
  [0, 1, 5],
  [0, 2, 3],
  [1, 3, 6],
  [1, 2, 2],
  [2, 4, 4],
  [2, 5, 2],
  [2, 3, 7],
  [3, 4, -1],
  [4, 5, -2]
];

console.log(shortestPathDAG(n, edges, 0));
A[0, 5, 3, 13, 12, 10]
B[0, 5, 3, 11, 10, 8]
C[0, 5, 3, 10, 7, 5]
D[0, 5, 3, 10, 9, 7]
Attempts:
2 left
💡 Hint
Trace the graph edges and update distances in topological order starting from source 0.
🧠 Conceptual
intermediate
1:30remaining
Why does topological order help in shortest path for DAG?
Why is using topological order important when finding shortest paths in a Directed Acyclic Graph (DAG)?
ABecause it detects cycles in the graph to prevent infinite loops.
BBecause it ensures nodes are processed only after all their predecessors, allowing correct distance updates without revisiting nodes.
CBecause it sorts nodes by their distance values automatically.
DBecause it guarantees the graph is weighted positively.
Attempts:
2 left
💡 Hint
Think about how processing nodes in order affects distance relaxation.
🔧 Debug
advanced
2:00remaining
Identify the bug causing incorrect shortest path output
The following TypeScript code attempts to find shortest paths in a DAG but produces incorrect results. What is the bug?
DSA Typescript
function shortestPathBug(n: number, edges: [number, number, number][], src: number): number[] {
  const graph = new Map<number, [number, number][]>();
  for (let i = 0; i < n; i++) graph.set(i, []);
  for (const [u, v, w] of edges) {
    graph.get(u)!.push([v, w]);
  }

  const visited = new Array(n).fill(false);
  const stack: number[] = [];

  function dfs(node: number) {
    visited[node] = true;
    for (const [nbr] of graph.get(node)!) {
      if (!visited[nbr]) dfs(nbr);
    }
    stack.push(node);
  }

  for (let i = 0; i < n; i++) {
    if (!visited[i]) dfs(i);
  }

  const dist = new Array(n).fill(Infinity);
  dist[src] = 0;

  while (stack.length) {
    const node = stack.pop()!;
    if (dist[node] !== Infinity) {
      for (const [nbr, w] of graph.get(node)!) {
        if (dist[node] + w < dist[nbr]) {
          dist[nbr] = dist[node] + w;
        }
      }
    }
  }

  return dist;
}
ANot marking nodes as visited before DFS causes infinite recursion.
BNot initializing dist[src] to 0 causes all distances to remain Infinity.
CUsing stack.pop() instead of stack.shift() causes nodes to be processed in reverse order.
DUsing stack.unshift(node) instead of stack.push(node) in DFS reverses topological order causing incorrect processing.
Attempts:
2 left
💡 Hint
Check how nodes are added to the stack during DFS and how that affects order.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in the shortest path code snippet
Which option contains a syntax error preventing the shortest path code from compiling?
DSA Typescript
const graph = new Map<number, [number, number][]>()
for (let i = 0; i < n; i++) {
  graph.set(i, [])
}
for (const [u, v, w] of edges) {
  graph.get(u)!.push([v, w])
}

const dist = new Array(n).fill(Infinity)
dist[src] = 0

while (stack.length) {
  const node = stack.pop()!
  if (dist[node] !== Infinity) {
    for (const [nbr, w] of graph.get(node)!) {
      if (dist[node] + w < dist[nbr]) {
        dist[nbr] = dist[node] + w
      }
    }
  }
}
Aconst dist = new Array(n).fill(Infinity) dist[src] = 0 // Missing semicolon between statements
Bfor (const [nbr, w] of graph.get(node)!) { if (dist[node] + w < dist[nbr]) { dist[nbr] = dist[node] + w } } // Correct syntax
Cfor (const [u, v, w] of edges) { graph.get(u)!.push([v, w]) } // Missing semicolon causes syntax error
Dconst node = stack.pop()! // The exclamation mark is invalid syntax in TypeScript
Attempts:
2 left
💡 Hint
Look for missing punctuation between statements.
🚀 Application
expert
2:00remaining
Calculate number of nodes reachable with finite shortest path
After running shortest path in a DAG from source 0, how many nodes have a finite shortest distance (not Infinity) given the edges below?
DSA Typescript
const n = 7;
const edges: [number, number, number][] = [
  [0, 1, 2],
  [0, 2, 4],
  [1, 3, 7],
  [2, 4, 1],
  [4, 3, 2],
  [5, 6, 3]
];

// Run shortest path from source 0 using topological order
// Count nodes with dist[node] !== Infinity
A5
B6
C4
D7
Attempts:
2 left
💡 Hint
Nodes 5 and 6 are disconnected from source 0.