Degrees of Separation Between Two Users With Bidirectional BFS
Last updated: November 29, 2026
Quick Overview
Given an undirected friendship graph as an adjacency map, return the minimum number of friendship hops between user A and user B, or -1 if they are not connected.
Meta
November 29, 20260
0
0 solved
Given an undirected friendship graph as an adjacency map, return the minimum number of friendship hops between user A and user B, or -1 if they are not connected.
Degrees of separation is a classic Facebook graph question, posed here in the style of Meta's onsite where the follow-up is always scale. The interviewer expects plain BFS first, then bidirectional BFS that expands the smaller frontier, because average degree in the social graph is in the hundreds.
What the Interviewer Expects
- Gives single-source BFS as the baseline
- Explains the b^d vs 2 * b^(d/2) frontier argument
- Expands the smaller frontier each round
- Detects meeting by checking the other side's visited set
- Handles A equal to B and unknown users
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you return one shortest friendship chain?
- How would you serve this query when the graph is sharded across machines?
- How would you cap the search to six degrees to bound latency?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: graph as dict user -> list of friends (symmetric), and users a, b. Output: hop count or -1. Graph may have hundreds of millions of nodes in production, so the algorithm should explore as ...
High-Level Design
Keep two visited maps, da from a and db from b, each storing distance. Each round, expand the side with the smaller frontier by one full level. When a newly reached node already appears in the oth...