Facebook Pixel

Shortest Distance from Source (BFS)

JavaScript
medium
30 mins

Given a directed graph represented as an adjacency list graph and a source node src, return an array dist where dist[i] represents the shortest distance (number of edges) from src to node i. If node i is unreachable from src, dist[i] should be Infinity. The distance from src to itself is 0.

Examples

Input: graph = [[1, 2], [3], [4], [5], [3], []], src = 0 Output: [0, 1, 1, 2, 2, 3] Explanation: - Distance from 0 to 0: 0 (same node) - Distance from 0 to 1: 1 (direct edge) - Distance from 0 to 2: 1 (direct edge) - Distance from 0 to 3: 2 (0 -> 1 -> 3 or 0 -> 2 -> 4 -> 3) - Distance from 0 to 4: 2 (0 -> 2 -> 4) - Distance from 0 to 5: 3 (0 -> 1 -> 3 -> 5)
Input: graph = [[1], [2], []], src = 0 Output: [0, 1, 2] Explanation: Linear path 0 -> 1 -> 2
Input: graph = [[1], [2], []], src = 2 Output: [Infinity, Infinity, 0] Explanation: Node 2 cannot reach nodes 0 or 1
Input: graph = [[1], [2], [0]], src = 0 Output: [0, 1, 2] Explanation: Graph with cycle, but shortest distances are still valid

Constraints

  • Graph is represented as an adjacency list where graph[i] contains all nodes reachable from node i
  • Nodes are numbered from 0 to n-1 where n is the number of nodes
  • Graph may contain cycles
  • Graph may be disconnected
  • Distance from src to itself is always 0
  • Unreachable nodes have distance Infinity
  • Input validation: handle invalid inputs gracefully (non-array graph, invalid node indices)

Function Signature

function shortestDistance(graph, src) { // Your code here }

Test Cases

  • Base cases: single node graph [[], 0] -> [0]
  • Direct neighbors: [[1, 2], [], []], 0 -> [0, 1, 1]
  • Multi-hop paths: [[1], [2], [3], []], 0 -> [0, 1, 2, 3]
  • Disconnected nodes: [[1], [], [3], []], 0 -> [0, 1, Infinity, Infinity]
  • Graph with cycle: [[1], [2], [0]], 0 -> [0, 1, 2]
  • Source with no outgoing edges: [[], [0], []], 1 -> [1, 0, Infinity]
  • Large graphs with multiple paths

Companies:

amazon
flipkart
zomato
phonepe
microsoft

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.