Minimum Follow Hops Between Two Creators Using Bidirectional BFS
Last updated: November 29, 2026
Quick Overview
Given a directed follow graph as adjacency lists (who each user follows) and two user IDs, return the minimum number of follow hops from the source to the target, or -1 if unreachable. The graph is huge, so explain how you keep the search small.
TikTok
November 29, 20260
0
0 solved
Given a directed follow graph as adjacency lists (who each user follows) and two user IDs, return the minimum number of follow hops from the source to the target, or -1 if unreachable. The graph is huge, so explain how you keep the search small.
TikTok's social graph powers features like suggested accounts and 'people you may know', and degree-of-separation queries are a common onsite graph prompt. The interviewer wants a correct BFS first, then the insight that searching from both ends shrinks the frontier dramatically on high-fanout graphs.
What the Interviewer Expects
- Starts with plain BFS and explains why DFS does not give shortest paths
- Builds a reverse adjacency to search backward from the target on a directed graph
- Expands the smaller frontier each round in bidirectional search
- Detects the meeting point correctly and returns the summed depth
- Discusses why bidirectional search helps with fanout b: roughly 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
- How would you return the actual path, not just the length?
- Celebrity accounts follow or are followed by millions; how do you avoid expanding them?
- How would you serve this query with low latency on a sharded graph store?
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:
follows: dict[int, list[int]](u follows v means edge u to v),src,dst. - Output: number of edges on the shortest path, 0 if
src == dst, -1 if none. - Unweighted edges, so BFS gives ...
High-Level Design
Plain BFS from src is correct but explores b^d nodes. Bidirectional BFS runs one search forward from src on follow edges and one backward from dst on reversed edges. Each round I expand one full...