Implement Social Graph Snapshot Queries
OpenAISoftware Engineer · Technical ScreenLast updated
This problem tests your ability to design a query-optimized representation for a directed graph, specifically focusing on efficient retrieval of multi-hop relationships and neighbor-based ranking.
Problem Statement
You are building an analytics service for a social network. The network can be modeled as a directed graph where an edge from A to B represents that A follows B. The graph is static (no updates once loaded).
Implement a class SocialGraph that supports efficient queries:
get_following(user_id): Returns a list of users thatuser_idfollows.get_second_degree_suggestions(user_id): Returns a list of potential accounts to follow. A 'second-degree suggestion' is defined as a user that a personuser_idfollows also follows, excluding usersuser_idalready follows and theuser_idthemselves. Suggestions should be ranked by the number of mutual connections (i.e., how many peopleuser_idfollows who also follow the suggestion).
Implementation Signature
class SocialGraph:
def __init__(self, follows: list[tuple[int, int]]):
# Initialize the graph structure
pass
def get_following(self, user_id: int) -> list[int]:
# Return list of user_ids followed by user_id
pass
def get_second_degree_suggestions(self, user_id: int) -> list[int]:
# Return ranked list of suggestions
pass
Constraints
N(number of users) up to 10^5.E(number of edges) up to 10^6.- Time limit: 2 seconds per query for suggestions.
Example
Input: [(1, 2), (1, 3), (2, 4), (3, 4), (3, 5)]
get_following(1)->[2, 3]get_second_degree_suggestions(1)->[4 (score 2), 5 (score 1)]Explanation: 1 follows 2 and 3. Both 2 and 3 follow 4 (score 2). Only 3 follows 5 (score 1).
Hints
Hint 1
Represent the graph using an adjacency list where each user maps to a set of followed users for O(1) lookups.
Hint 2
For second-degree suggestions, iterate through the list of followed users, then iterate through their respective followings to count occurrences.
Hint 3
Use a hash map to maintain the frequency count of each potential candidate to aggregate scores in linear time relative to the degree of neighbors.
Follow-up questions
- How would your approach change if the graph were dynamic and edges were added or removed frequently?
- What are the memory complexity trade-offs if you precompute all second-degree suggestions during initialization?
- How would you handle a scenario where the number of second-degree connections is extremely large, making the result list too slow to sort?
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.