Problem Breakdown
Friend Recommender
Graph Search & Pathfinding
Published ·
medium
Try This Problem Yourself
Practice in the AI-enabled editor with real-time feedback
You're given a social network, which is a collection of users and their bidirectional friendships. For a given user, return up to 5 recommended friends ranked by the number of mutual friends they share with the user. Ties break alphabetically by name. The user cannot be recommended to themselves, existing friends are excluded, and candidates must share at least one mutual friend.
Small social graph with Alice at the center, her three direct friends in the inner ring, and her three recommendations Eve, Frank, and Grace highlighted on the outer ring
The code is split across two classes. SocialNetwork owns the adjacency data and exposes helpers for fetching a user's friends, counting mutuals between two users, and checking whether a candidate is a valid recommendation. Recommender holds a reference to one SocialNetwork and implements a single recommend method that takes a user and a maximum result count. Every solution below lives inside that one method.
Solution 1, scan every user
The most natural solution is the literal restatement of the rules. You walk every user in the network, skip the invalid ones, count mutuals for each valid one, sort by those counts, and take the top five. The validity helper already combines the three exclusion rules into a single call, so the outer loop stays a clean filter.
Complexity
Where it breaks
Solution 2, walk friends-of-friends
Complexity
Where it lands
Benchmarks
Takeaways
Purchase Premium to Keep Reading
Unlock this article and so much more with Hello Interview Premium
Reading Progress
On This Page