Follow Graph: Following Lists and Mutual-Count Suggestions
Trees & GraphsAuto-graded · 13 test casesLast updated
Answer batched queries on a static directed follow graph: list direct followees and rank second-hop accounts by how many followees also follow them.
A social app stores who follows whom as a fixed, directed graph. Each pair [a, b] in follows means that user a follows user b. The graph never changes after it is given.
You receive the edge list together with a batch of queries. Answer every query in order and return all the answers.
Queries
Query i is made of operations[i] (its name) and arguments[i] (a list whose first element is the user id u being asked about).
"get_following": return the users thatufollows, in the order their edges appear infollows."get_second_degree_suggestions": return accountsumight want to follow. A usercis a candidate if some userfthatufollows also followsc, andcis neitherunor already followed byu.- The score of a candidate is the number of paths
u -> f -> c, that is, how many ofu's followees followc. - Return the candidates sorted by score from highest to lowest. Candidates with equal scores are sorted by user id from smallest to largest.
- Return only user ids, not scores.
- The score of a candidate is the number of paths
Rules and edge cases
- A user that never appears as a follower (no outgoing edges), or does not appear in the graph at all, yields
[]for both query types. - Edges are used exactly as given. If the same pair appears several times, each occurrence is a separate edge: it appears repeatedly in
get_followingand counts separately toward scores. - A self-loop
[x, x]is a normal edge, so it appears inget_following(x). A user is never suggested to themselves. - A name other than the two above is invalid input and should raise
ValueError.
Output
Return a list with one entry per query, in the same order. Each entry is a list of integers.
Constraints
- Up to
10^5users and up to10^6edges. len(operations) == len(arguments), and eacharguments[i]holds the single user idu.- Each suggestion query should take about 2 seconds at most, so build the adjacency structure once and do not rescan the whole edge list per query.
Examples
Example 1
Input: follow_graph_queries([[1, 2], [1, 3], [2, 4], [3, 4], [3, 5]], ['get_following', 'get_second_degree_suggestions'], [[1], [1]])
Output: [[2, 3], [4, 5]]
Hints
Hint 1
Build an adjacency list from follower to followees once, before processing any query.
Hint 2
For a suggestion query, put u's direct followees in a set so you can exclude them in O(1), then walk each followee's own followees and increment a counter.
Hint 3
Skip a candidate if it equals u or is in the direct set. Sort the counter's keys by the pair (-score, user_id) to get the required ordering.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The graph is static, so the work splits into two parts.
- Build once. Create a dictionary mapping each follower to the list of users they follow, preserving the order of the input edges. Edges are kept exactly as given, so repeated pairs stay repeated.
- Answer each query from that map.
get_followingreturns a copy of the stored list, or[]if the user has no entry.get_second_degree_suggestionsfirst putsu's direct followees into a set for constant-time exclusion. It then loops over each followeefofu, and over each usercthatffollows. Ifcis notuand not in the direct set, it adds 1 toscores[c]. Finally it sorts the candidates by(-score, id).
Lookups use .get(..., []) so that querying an unknown user does not insert new keys into the graph.
Why it is correct
- Every valid candidate
ccorresponds to at least one pathu -> f -> c, and the double loop visits every such path, so no candidate is missed. - Each path increments the candidate's counter once, so the final score is exactly the number of such paths, which is the mutual-connection count under the edge rules above.
- Users who are
uor already followed byuare filtered before they reach the counter, so they never appear in the output. - Sorting by
(-score, id)gives highest score first and breaks ties by the smaller id, which makes the output deterministic.
Complexity
Let E be the number of edges, W the number of 2-hop paths from u (the sum of out-degrees of u's followees), and K the number of distinct candidates (K <= W).
- Build: O(E) time, O(E) space.
get_following: O(d(u)) time and space for the copy.get_second_degree_suggestions: O(W + K log K) time, O(K + d(u)) space. SinceW <= E, this fits the 2-second limit for up to 10^6 edges.
Reference solution
from collections import defaultdict
from typing import List
def follow_graph_queries(follows: List[List[int]], operations: List[str], arguments: List[List[int]]) -> List[List[int]]:
graph = defaultdict(list)
for follower, followee in follows:
graph[follower].append(followee)
answers = []
for op, args in zip(operations, arguments):
u = args[0]
if op == "get_following":
answers.append(list(graph.get(u, [])))
elif op == "get_second_degree_suggestions":
direct_list = graph.get(u, [])
direct = set(direct_list)
scores = defaultdict(int)
for f in direct_list:
for c in graph.get(f, []):
if c != u and c not in direct:
scores[c] += 1
answers.append(sorted(scores, key=lambda c: (-scores[c], c)))
else:
raise ValueError("Unknown operation")
return answers