Bird
Raised Fist0
DSA Javascriptprogramming

Why Shortest Path Is a Graph Problem Not a Tree Problem in DSA Javascript - Why This Pattern

Choose your learning style10 modes available
Mental Model
Shortest path means finding the quickest way between two points, but trees have only one path between nodes, while graphs can have many paths and loops.
Analogy: Imagine city streets: a tree is like a single straight road with no turns, but a graph is like a city map with many roads and intersections where you can choose different routes.
Tree:
1 -> 2 -> 3 -> null

Graph:
1 -> 2 -> 3
↓    ↑
4 ← 5
Dry Run Walkthrough
Input: Graph with nodes 1, 2, 3, 4, 5 and edges: 1->2, 1->4, 2->3, 3->5, 4->5, 5->4, 4->1; find shortest path from 1 to 5
Goal: Show why shortest path needs graph handling because multiple routes exist, unlike a tree
Step 1: Start at node 1, check neighbors
1 [start] -> 2, 4
2 -> 3
3 -> 5
5 -> 4
4 -> 1
Why: We begin from the start node and look at all possible next steps
Step 2: From node 1, explore node 2 first
1 -> [2] -> 3
4 -> 1
5 -> 4
3 -> 5
Why: We follow one path to see if it leads to the target
Step 3: From node 2, move to node 3
1 -> 2 -> [3] -> 5
4 -> 1
5 -> 4
Why: Continue along the path to get closer to node 5
Step 4: From node 3, move to node 5 (target)
1 -> 2 -> 3 -> [5]
4 -> 1
Why: We reached the target node following one path
Step 5: Check alternative path from node 1 to 4 to 5
1 -> [4] -> 5
2 -> 3
3 -> 5
5 -> 4
Why: Graph allows multiple paths; we check if this is shorter
Step 6: From node 4, move to node 5
1 -> 4 -> [5]
2 -> 3
3 -> 5
5 -> 4
Why: Alternative path found; compare lengths
Result:
Shortest path is 1 -> 4 -> 5 or 1 -> 2 -> 3 -> 5; graph allows multiple paths unlike tree
Annotated Code
DSA Javascript
class Graph {
  constructor() {
    this.adjList = new Map();
  }

  addEdge(u, v) {
    if (!this.adjList.has(u)) this.adjList.set(u, []);
    this.adjList.get(u).push(v);
  }

  shortestPath(start, end) {
    const queue = [start];
    const visited = new Set([start]);
    const parent = new Map();

    while (queue.length > 0) {
      const node = queue.shift();
      if (node === end) break;
      for (const neighbor of (this.adjList.get(node) || [])) {
        if (!visited.has(neighbor)) {
          visited.add(neighbor);
          parent.set(neighbor, node);
          queue.push(neighbor);
        }
      }
    }

    if (!parent.has(end) && start !== end) return 'No path';

    const path = [];
    let current = end;
    while (current !== undefined) {
      path.push(current);
      current = parent.get(current);
    }
    path.reverse();
    return path.join(' -> ') + ' -> null';
  }
}

// Driver code
const graph = new Graph();
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 5);
graph.addEdge(5, 4);
graph.addEdge(4, 1);
graph.addEdge(1, 4);
graph.addEdge(4, 5);

console.log(graph.shortestPath(1, 5));
const queue = [start];
Initialize queue with start node to begin breadth-first search
const visited = new Set([start]);
Mark start node as visited to avoid revisiting
while (queue.length > 0) {
Loop until all reachable nodes are explored or target found
const node = queue.shift();
Dequeue next node to explore neighbors
if (node === end) break;
Stop search when target node is found
for (const neighbor of (this.adjList.get(node) || [])) {
Check all neighbors of current node
if (!visited.has(neighbor)) {
Visit unvisited neighbors only
parent.set(neighbor, node);
Record path by storing parent of each visited node
const path = []; let current = end; while (current !== undefined) { path.push(current); current = parent.get(current); }
Reconstruct shortest path by backtracking from end to start
OutputSuccess
1 -> 4 -> 5 -> null
Complexity Analysis
Time: O(V + E) because we visit each node and edge once during breadth-first search
Space: O(V) for storing visited nodes, queue, and parent map
vs Alternative: Unlike trees with one path, graphs need BFS to handle multiple paths and cycles efficiently
Edge Cases
No path exists between start and end
Function returns 'No path' indicating unreachable target
DSA Javascript
if (!parent.has(end) && start !== end) return 'No path';
Start and end are the same node
Returns the start node as the path
DSA Javascript
if (!parent.has(end) && start !== end) return 'No path';
Graph with cycles
Visited set prevents infinite loops by not revisiting nodes
DSA Javascript
if (!visited.has(neighbor)) { visited.add(neighbor); ... }
When to Use This Pattern
When a problem asks for shortest path in a structure with possible loops or multiple routes, use graph traversal like BFS because trees have only one path and no cycles.
Common Mistakes
Mistake: Trying to find shortest path assuming the structure is a tree with only one path
Fix: Use graph traversal algorithms like BFS to handle multiple paths and cycles
Mistake: Not marking visited nodes causing infinite loops in cyclic graphs
Fix: Maintain a visited set to avoid revisiting nodes
Summary
Shortest path problems require graph algorithms because graphs can have multiple paths and cycles.
Use graph traversal like BFS when multiple routes or loops exist between points.
The key insight is that trees have only one path between nodes, but graphs can have many, so shortest path needs graph handling.

Practice

(1/5)
1. Why is finding the shortest path usually considered a graph problem rather than a tree problem?
easy
A. Because trees do not have nodes
B. Because trees always have equal path lengths
C. Because shortest path algorithms only work on trees
D. Because graphs can have cycles and multiple paths between nodes, unlike trees

Solution

  1. Step 1: Understand the structure of trees and graphs

    Trees are a special type of graph with no cycles and exactly one path between any two nodes.
  2. Step 2: Analyze shortest path requirements

    Shortest path problems require handling multiple paths and cycles, which only general graphs can have.
  3. Final Answer:

    Because graphs can have cycles and multiple paths between nodes, unlike trees -> Option D
  4. Quick Check:

    Graphs allow multiple paths = shortest path problem [OK]
Hint: Shortest path needs multiple paths; trees have only one [OK]
Common Mistakes:
  • Thinking trees have cycles
  • Assuming shortest path only applies to trees
  • Confusing nodes with edges
2. Which of the following is the correct way to represent a graph in JavaScript for shortest path algorithms?
easy
A. const graph = { A: ['B', 'C'], B: ['A'], C: ['A'] };
B. const graph = ['A', 'B', 'C'];
C. const graph = { A: 1, B: 2, C: 3 };
D. const graph = [ ['A', 'B'], ['B', 'C'] ];

Solution

  1. Step 1: Identify graph representation formats

    Graphs are often represented as adjacency lists, where each node maps to an array of connected nodes.
  2. Step 2: Match the correct JavaScript syntax

    const graph = { A: ['B', 'C'], B: ['A'], C: ['A'] }; uses an object with keys as nodes and arrays as neighbors, which is a valid adjacency list.
  3. Final Answer:

    const graph = { A: ['B', 'C'], B: ['A'], C: ['A'] }; -> Option A
  4. Quick Check:

    Adjacency list = object with arrays [OK]
Hint: Adjacency list uses object keys with neighbor arrays [OK]
Common Mistakes:
  • Using arrays without keys for adjacency
  • Confusing node labels with values
  • Using arrays of nodes without connections
3. Consider the following graph represented as an adjacency list:
const graph = { A: ['B', 'C'], B: ['A', 'D'], C: ['A', 'D'], D: ['B', 'C'] };

Using a shortest path algorithm from node 'A' to 'D', what is the length of the shortest path?
medium
A. 2
B. 3
C. 1
D. 4

Solution

  1. Step 1: List all paths from 'A' to 'D'

    Possible paths: A->B->D and A->C->D, both have 2 edges.
  2. Step 2: Determine shortest path length

    Both paths have length 2, so shortest path length is 2.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Shortest path edges count = 2 [OK]
Hint: Count edges in shortest route from start to end [OK]
Common Mistakes:
  • Counting nodes instead of edges
  • Ignoring multiple paths
  • Assuming direct edge exists
4. The following code attempts to find the shortest path length in a graph but has a bug:
function shortestPath(graph, start, end) {
  let queue = [start];
  let visited = new Set();
  let distance = {};
  distance[start] = 0;

  while (queue.length > 0) {
    let node = queue.shift();
    if (node === end) return distance[node];
    for (let neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        distance[neighbor] = distance[node] + 1;
        queue.push(neighbor);
      }
    }
  }
  return -1;
}

What is the main bug in this code?
medium
A. The distance object is not updated
B. The queue is not initialized correctly
C. The visited set is never updated for the start node
D. The function does not return anything

Solution

  1. Step 1: Check visited set usage

    The start node is added to the queue but not marked visited initially, so it may be revisited.
  2. Step 2: Understand BFS behavior

    Without marking start visited, neighbors may be processed multiple times, causing incorrect distances or infinite loops.
  3. Final Answer:

    The visited set is never updated for the start node -> Option C
  4. Quick Check:

    Start node must be visited first [OK]
Hint: Always mark start node visited before BFS loop [OK]
Common Mistakes:
  • Forgetting to mark start visited
  • Assuming queue initialization fixes visited
  • Ignoring visited set usage
5. You have a graph with weighted edges, and some edges form cycles. Why can't you use a simple tree shortest path algorithm here, and which algorithm is suitable instead?
hard
A. Because trees have weighted edges; use Prim's algorithm for shortest path
B. Because trees have no cycles; use Dijkstra's algorithm for weighted graphs with cycles
C. Because trees allow multiple paths; use DFS for weighted graphs
D. Because trees have cycles; use BFS for weighted graphs

Solution

  1. Step 1: Understand tree vs graph with cycles and weights

    Trees have no cycles and unweighted edges, so simple shortest path methods for trees don't apply to weighted graphs with cycles.
  2. Step 2: Identify suitable algorithm for weighted graphs with cycles

    Dijkstra's algorithm handles weighted edges and cycles correctly to find shortest paths.
  3. Final Answer:

    Because trees have no cycles; use Dijkstra's algorithm for weighted graphs with cycles -> Option B
  4. Quick Check:

    Weighted graph + cycles = Dijkstra's algorithm [OK]
Hint: Use Dijkstra for weighted graphs with cycles, not tree methods [OK]
Common Mistakes:
  • Using BFS for weighted graphs
  • Confusing Prim's algorithm with shortest path
  • Ignoring cycles in graph
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