HardPro challengePythonJavaScriptTypeScript

Graph BFS Shortest Path

Data StructuresGraphBFSAlgorithms

Build an undirected, unweighted graph from an edge list and find the
shortest path (minimum number of edges) between two nodes using BFS.

Graph class

class Graph {
  addEdge(u, v)            // register undirected edge u ↔ v
  bfs(source, target)      // → hop count, or -1 if unreachable
}

Store adjacency lists in a Map<string, string[]>.

solve(edges, source, target) builds the graph, then returns bfs(source, target).

Examples

// Direct edge
solve([['A','B'],['B','C'],['A','C']], 'A', 'C')  → 1

// Two hops
solve([['A','B'],['B','C']], 'A', 'C')             → 2

// Disconnected
solve([['A','B'],['C','D']], 'A', 'C')             → -1

// Same node
solve([['A','B']], 'A', 'A')                        → 0

Constraints

  • Node identifiers are strings.
  • The graph may contain cycles — use a visited set to avoid infinite loops.
  • If source has no edges at all and source ≠ target, return -1.

Sample tests

Test #1Direct edge A→C exists even though A→B→C is also valid
Input: [[["A","B"],["B","C"],["A","C"]],"A","C"]
Output: 1
Test #2Two hops — no direct edge between A and C
Input: [[["A","B"],["B","C"]],"A","C"]
Output: 2
Test #3Disconnected components — no path exists
Input: [[["A","B"],["C","D"]],"A","C"]
Output: -1