Degrees of Separation Between Two Pinners via Bidirectional BFS
Last updated: November 29, 2026
Quick Overview
Given a follow graph of Pinners, return the minimum number of hops between two users when a connection exists if either follows the other, or -1 if they are not connected. Aim for an approach that stays fast on a graph with hundreds of millions of users.
0
0
0 solved
Given a follow graph of Pinners, return the minimum number of hops between two users when a connection exists if either follows the other, or -1 if they are not connected. Aim for an approach that stays fast on a graph with hundreds of millions of users.
Social features like 'followed by people you know' depend on short path queries over the Pinterest follow graph. Onsite coding interviewers use this to see a correct BFS first, then whether you can explain and implement the bidirectional optimization that keeps the explored frontier small on a high-degree graph.
What the Interviewer Expects
- Builds an undirected adjacency from directed follows
- Implements level-by-level BFS from both ends and always expands the smaller frontier
- Finishes the whole level before returning so the answer is truly minimal
- Handles same user, missing users, and disconnected pairs
- Explains the complexity gain from b^(d/2) instead of b^d
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
- Why can returning at the first meeting edge mid-level give a wrong answer?
- How would you cap the search to at most 3 hops for a product feature?
- How would you serve this when the graph does not fit on one machine?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Graph: dict of user to list of followed users. Connection is undirected for this feature.
- Return min hops, 0 if a equals b, -1 if unreachable or either user is unknown....
High-Level Design
Plain BFS from a explores roughly b^d nodes for branching factor b and distance d. Running BFS from both a and b and stopping when the frontiers meet explores about 2 * b^(d/2). Each step expands one ...