mediumSoftware EngineerSocial Media
Explain BFS and DFS — when would you use each in a real application?
Posted 18/04/2026
by Mehedy Hasan Ador
Question Details
"Find shortest connection path between two users (LinkedIn-style). BFS or DFS?"
Suggested Solution
BFS (shortest path guaranteed): Queue, level-by-level.
DFS (any path): Stack/recursion, go deep.
Use BFS DFS
Shortest path ✅ ❌
Cycle detection ✅ ✅
Topological sort ❌ ✅
DFS (any path): Stack/recursion, go deep.
function bfs(graph, start, target) {
const queue = [start], visited = new Set([start]);
while (queue.length) {
const node = queue.shift();
if (node === target) return true;
for (const n of graph[node]) if (!visited.has(n)) { visited.add(n); queue.push(n); }
}
}
LinkedIn connections: BFS — explores level by level, first match = shortest path.