Implement Social Follow Recommendations
OpenAISoftware Engineer · Technical ScreenLast updated
This problem tests your ability to navigate a social graph to implement a recommendation system using set operations and frequency counting.
Problem Statement
You are tasked with building a 'Follow Recommendations' feature for a social media platform. You are given a directed graph represented by a dictionary where keys are User IDs and values are sets of User IDs that the user is currently following.
Your goal is to implement a function get_recommendations(user_id, graph, n) that returns a list of the n most recommended users. A user Candidate is recommended for user_id if:
Candidateis not theuser_idand is not already followed byuser_id.Candidateis followed by at least one person thatuser_idfollows (a 'friend-of-a-friend').
The recommendation score is defined as the number of followed users that also follow the Candidate. If two candidates have the same score, rank them by their User ID in ascending order.
Function Signature
def get_recommendations(user_id: int, graph: dict[int, set[int]], n: int) -> list[int]:
Examples
Example 1:
graph = {1: {2, 3}, 2: {4}, 3: {4, 5}, 4: {5}}get_recommendations(1, graph, 2)- Output:
[4, 5] - Explanation: User 1 follows 2 and 3. User 2 follows 4; User 3 follows 4 and 5. Candidate 4 is followed by 2 and 3 (score 2). Candidate 5 is followed by 3 (score 1).
Constraints
- Number of users: up to 10,000.
- Total number of follows: up to 100,000.
nis a positive integer.
Edge Cases
- The
user_iddoes not exist in the graph. - No common followees exist.
- The recommended list size is smaller than
n.
Hints
Hint 1
Identify all users that the target user follows, then iterate through their respective follow lists to find candidates.
Hint 2
Use a frequency map (hash map) to count how many times each candidate appears across the target's followees' sets.
Hint 3
When sorting the results, ensure you handle the tie-breaking condition of the User ID correctly.
Follow-up questions
- How would you optimize the solution if the graph was too large to fit in memory and lived in a distributed database?
- What would be the time complexity of your solution in terms of the number of users (V) and edges (E)?
- If users have millions of followers, how would you prevent the 'celebrity follower' problem from slowing down your recommendations?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.