0
0
DSA Typescriptprogramming~10 mins

Why Shortest Path Is a Graph Problem Not a Tree Problem in DSA Typescript - Test Your Knowledge

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize an adjacency list for a graph with 3 nodes.

DSA Typescript
const graph: number[][] = [[], [], []];
graph[0].push([1]);
Drag options to blanks, or click blank then click option'
A2
B1
C0
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using node numbers outside the graph range.
Confusing node indices with edge weights.
2fill in blank
medium

Complete the code to check if a node has been visited in a graph traversal.

DSA Typescript
const visited: boolean[] = [false, false, false];
if (!visited[[1]]) {
  visited[1] = true;
}
Drag options to blanks, or click blank then click option'
A1
B0
C2
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using an index outside the visited array.
Checking the wrong node index.
3fill in blank
hard

Fix the error in the code that tries to find the shortest path in a graph using BFS.

DSA Typescript
const queue: number[] = [];
queue.push(0);
while (queue.length > 0) {
  const node = queue.shift()[1];
  // process node
}
Drag options to blanks, or click blank then click option'
A();
B[0]
C()
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting parentheses after shift.
Using incorrect syntax for method calls.
4fill in blank
hard

Fill both blanks to update distances and enqueue neighbors during BFS shortest path search.

DSA Typescript
for (const neighbor of graph[node]) {
  if (distances[neighbor] === [1]) {
    distances[neighbor] = distances[node] [2] 1;
    queue.push(neighbor);
  }
}
Drag options to blanks, or click blank then click option'
A-1
B+
C0
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of -1 for unvisited check.
Subtracting 1 instead of adding 1 to distance.
5fill in blank
hard

Fill all three blanks to create a function that returns the shortest path length from start to end in a graph.

DSA Typescript
function shortestPath(graph: number[][], start: number, end: number): number {
  const distances = Array(graph.length).fill([1]);
  const queue: number[] = [];
  distances[start] = 0;
  queue.push(start);
  while (queue.length > 0) {
    const node = queue.shift()[2];
    if (node === end) return distances[node];
    for (const neighbor of graph[node]) {
      if (distances[neighbor] === [3]) {
        distances[neighbor] = distances[node] + 1;
        queue.push(neighbor);
      }
    }
  }
  return -1;
}
Drag options to blanks, or click blank then click option'
A-1
B()
C0
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Not initializing distances with -1.
Forgetting parentheses on shift.
Checking for 0 instead of -1 for unvisited.