Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

BFS Breadth First Search on Graph in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
BFS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of BFS traversal on a simple graph
What is the output of the BFS traversal starting from node 0 in the given graph?
DSA Typescript
const graph = new Map<number, number[]>([
  [0, [1, 2]],
  [1, [0, 3]],
  [2, [0, 4]],
  [3, [1]],
  [4, [2]]
]);

function bfs(start: number, graph: Map<number, number[]>): number[] {
  const visited = new Set<number>();
  const queue: number[] = [];
  const order: number[] = [];

  visited.add(start);
  queue.push(start);

  while (queue.length > 0) {
    const node = queue.shift()!;
    order.push(node);
    for (const neighbor of graph.get(node) ?? []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return order;
}

console.log(bfs(0, graph));
A[0, 1, 2, 3, 4]
B[0, 2, 1, 4, 3]
C[0, 1, 3, 2, 4]
D[0, 2, 4, 1, 3]
Attempts:
2 left
💡 Hint
Remember BFS visits neighbors level by level, starting from the start node.
🧠 Conceptual
intermediate
1:30remaining
Number of nodes visited in BFS
Given a graph with 6 nodes (0 to 5) and edges: 0-1, 0-2, 1-3, 2-4, 4-5, how many nodes will BFS visit starting from node 0?
A4
B5
C6
D3
Attempts:
2 left
💡 Hint
BFS visits all nodes reachable from the start node.
❓ Predict Output
advanced
2:00remaining
BFS traversal order with disconnected graph
What is the output of BFS starting from node 0 on this graph with disconnected components?
DSA Typescript
const graph = new Map<number, number[]>([
  [0, [1]],
  [1, [0]],
  [2, [3]],
  [3, [2]]
]);

function bfs(start: number, graph: Map<number, number[]>): number[] {
  const visited = new Set<number>();
  const queue: number[] = [];
  const order: number[] = [];

  visited.add(start);
  queue.push(start);

  while (queue.length > 0) {
    const node = queue.shift()!;
    order.push(node);
    for (const neighbor of graph.get(node) ?? []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return order;
}

console.log(bfs(0, graph));
A[0, 1]
B[0, 1, 2, 3]
C[0]
D[1, 0]
Attempts:
2 left
💡 Hint
BFS only visits nodes reachable from the start node.
🔧 Debug
advanced
2:00remaining
Identify the error in BFS implementation
What error will this BFS code produce when run?
DSA Typescript
function bfs(start: number, graph: Map<number, number[]>): number[] {
  const visited = new Set<number>();
  const queue: number[] = [];
  const order: number[] = [];

  queue.push(start);

  while (queue.length > 0) {
    const node = queue.shift()!;
    order.push(node);
    for (const neighbor of graph.get(node) ?? []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return order;
}

console.log(bfs(0, new Map([[0, [1]], [1, [0]]])));
ARuntime error: Cannot read property 'get' of undefined
BInfinite loop because start node is never marked visited
CSyntaxError due to missing colon
DThe code runs correctly and outputs [0, 1]
Attempts:
2 left
💡 Hint
Check if the start node is marked visited before adding to queue.
🚀 Application
expert
2:30remaining
Shortest path length using BFS
Given the graph below, what is the shortest path length from node 0 to node 5 using BFS? Edges: 0-1, 0-2, 1-3, 2-4, 4-5
DSA Typescript
const graph = new Map<number, number[]>([
  [0, [1, 2]],
  [1, [0, 3]],
  [2, [0, 4]],
  [3, [1]],
  [4, [2, 5]],
  [5, [4]]
]);

function bfsShortestPath(start: number, end: number, graph: Map<number, number[]>): number {
  const visited = new Set<number>();
  const queue: Array<{node: number; dist: number}> = [];

  visited.add(start);
  queue.push({node: start, dist: 0});

  while (queue.length > 0) {
    const {node, dist} = queue.shift()!;
    if (node === end) {
      return dist;
    }
    for (const neighbor of graph.get(node) ?? []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push({node: neighbor, dist: dist + 1});
      }
    }
  }

  return -1; // if no path found
}

console.log(bfsShortestPath(0, 5, graph));
A2
B4
C-1
D3
Attempts:
2 left
💡 Hint
Trace the shortest path step by step from 0 to 5.

Practice

(1/5)
1. What does BFS (Breadth First Search) primarily use to keep track of nodes to visit next in a graph?
easy
A. A priority queue to select nodes by weight
B. A stack to process nodes in depth order
C. A hash map to store visited nodes only
D. A queue to process nodes level by level

Solution

  1. Step 1: Understand BFS traversal method

    BFS explores nodes level by level, so it needs a structure that processes nodes in the order they are discovered.
  2. Step 2: Identify the data structure used

    A queue follows First-In-First-Out (FIFO) order, which matches BFS's level order traversal.
  3. Final Answer:

    A queue to process nodes level by level -> Option D
  4. Quick Check:

    BFS uses a queue = A [OK]
Hint: BFS uses FIFO order, so it needs a queue [OK]
Common Mistakes:
  • Confusing BFS with DFS which uses a stack
  • Thinking BFS uses a priority queue
  • Assuming BFS only uses a visited set without a queue
2. Which of the following is the correct TypeScript syntax to initialize a queue for BFS using an array?
easy
A. const queue = new Queue<number>();
B. const queue: number[] = [];
C. let queue = {};
D. var queue = new ArrayQueue();

Solution

  1. Step 1: Recognize TypeScript array initialization

    To create a queue using an array, declare an array with type annotation and initialize it empty.
  2. Step 2: Check each option

    const queue: number[] = []; correctly declares an empty number array. const queue = new Queue<number>(); uses a class Queue which is not built-in. let queue = {}; initializes an object, not a queue. var queue = new ArrayQueue(); uses a non-existent ArrayQueue.
  3. Final Answer:

    const queue: number[] = []; -> Option B
  4. Quick Check:

    Array queue syntax = A [OK]
Hint: Use typed empty array for queue in TypeScript [OK]
Common Mistakes:
  • Using undefined classes like Queue without import
  • Initializing queue as an object {} instead of array
  • Using var instead of const or let (less preferred)
3. Given the graph adjacency list below and BFS starting from node 0, what is the order of nodes visited?
const graph = {
  0: [1, 2],
  1: [3],
  2: [3],
  3: []
};
medium
A. [0, 1, 2, 3]
B. [0, 2, 1, 3]
C. [0, 3, 1, 2]
D. [1, 2, 0, 3]

Solution

  1. Step 1: Start BFS from node 0

    Visit node 0 first, then enqueue its neighbors 1 and 2.
  2. Step 2: Visit neighbors in queue order

    Dequeue 1, visit it, enqueue its neighbor 3. Then dequeue 2, visit it, enqueue 3 again but already visited. Finally, dequeue 3.
  3. Final Answer:

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

    BFS order = [0, 1, 2, 3] [OK]
Hint: Visit nodes level by level, enqueue neighbors in order [OK]
Common Mistakes:
  • Visiting neighbors in wrong order
  • Visiting node 3 twice
  • Starting BFS from wrong node
4. Consider this BFS code snippet in TypeScript. What is the error?
function bfs(graph: Record, start: number) {
  const queue: number[] = [start];
  const visited = new Set<number>();
  while (queue.length > 0) {
    const node = queue.shift();
    if (!visited.has(node)) {
      visited.add(node);
      for (const neighbor of graph[node]) {
        queue.push(neighbor);
      }
    }
  }
  return Array.from(visited);
}
medium
A. queue.shift() can return undefined, causing errors
B. visited set is not updated correctly
C. Neighbors are not added to queue
D. Function does not return anything

Solution

  1. Step 1: Analyze queue.shift() usage

    queue.shift() returns number | undefined. If queue is empty, node can be undefined, causing errors when accessing graph[node].
  2. Step 2: Identify missing check for undefined

    Code should check if node is undefined before using it. Without this, runtime error can occur.
  3. Final Answer:

    queue.shift() can return undefined, causing errors -> Option A
  4. Quick Check:

    Check for undefined after shift = B [OK]
Hint: Always check queue.shift() result for undefined [OK]
Common Mistakes:
  • Ignoring possible undefined from shift()
  • Assuming visited set is wrong when it is correct
  • Thinking neighbors are not added when they are
5. You want to find the shortest path length from node 0 to node 4 in this graph using BFS:
const graph = {
  0: [1, 2],
  1: [3],
  2: [3, 4],
  3: [4],
  4: []
};
Which BFS modification helps find the shortest path length correctly?
hard
A. Ignore visited set to explore all paths
B. Use a stack instead of a queue
C. Track distance for each node when first visited
D. Visit nodes multiple times to update distance

Solution

  1. Step 1: Understand BFS for shortest path

    BFS finds shortest paths in unweighted graphs by exploring neighbors level by level.
  2. Step 2: Track distance when visiting nodes

    Maintain a distance map or array to record the number of edges from start node to each node when first visited.
  3. Final Answer:

    Track distance for each node when first visited -> Option C
  4. Quick Check:

    Distance tracking in BFS = D [OK]
Hint: Store distance on first visit to each node [OK]
Common Mistakes:
  • Using stack breaks BFS order
  • Visiting nodes multiple times wastes time
  • Ignoring visited set causes infinite loops
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