Batch Processor for a Directed Follow Graph
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a sequence of follow, unfollow, and query operations on a directed user graph, keeping outgoing and incoming edge views consistent and returning sorted results.
Follow Graph Simulator
You are building the core of a "who follows whom" service. Relationships are directed: if user a follows user b, that says nothing about whether b follows a.
Rather than writing a class, you will implement a single function that replays a list of operations against an initially empty graph and reports the outcome of each one.
Input
operations: a list of strings. Each string is one of"follow","unfollow","get_following","get_followers","is_following".arguments: a list of the same length asoperations. The entry at indexiholds the integer arguments foroperations[i].
Operations
Process the operations in order. For each operation, append exactly one value to the result list.
| Operation | Arguments | Effect | Value appended |
|---|---|---|---|
follow | [follower, followee] | Adds the directed edge follower -> followee. If the edge is already present, nothing changes. | None |
unfollow | [follower, followee] | Removes the edge follower -> followee. If the edge is not present, nothing changes. | None |
get_following | [user] | Looks up every user that user currently follows. | A list of those user IDs in ascending order |
get_followers | [user] | Looks up every user that currently follows user. | A list of those user IDs in ascending order |
is_following | [follower, followee] | Checks whether the edge follower -> followee currently exists. | True or False |
Rules and edge cases
- A user may follow themselves. Such a self-edge is a normal edge: it appears in both that user's following list and their followers list, and
unfollowremoves it. - Repeating
followfor an existing edge never creates duplicates. - Calling
unfollowfor an edge that does not exist (including when either user has never been seen) does nothing and is not an error. - Querying a user who has no edges, or who has never appeared, returns an empty list for the two list queries and
Falseforis_following. - Lists returned by
get_followingandget_followersmust be sorted ascending and contain no duplicates.
Output
Return a list with one entry per operation, in the same order as the input.
Constraints
len(operations) == len(arguments).- All user IDs are positive integers.
- The number of users and edges can be very large, so each
follow,unfollow, andis_followingshould take roughly constant time on average, and no operation should scan all users. - Both list queries should only do work proportional to the size of the answer (plus sorting it).
Examples
Example 1
Input: run_follow_graph_ops(['follow', 'follow', 'follow', 'get_following', 'get_followers', 'is_following'], [[1, 2], [1, 3], [2, 1], [1], [1], [1, 2]])
Output: [None, None, None, [2, 3], [2], True]
Example 2
Input: run_follow_graph_ops(['get_following', 'get_followers', 'is_following'], [[99], [99], [99, 100]])
Output: [[], [], False]
Example 3
Input: run_follow_graph_ops(['follow', 'follow', 'follow', 'unfollow', 'get_following', 'get_followers'], [[5, 5], [5, 7], [5, 7], [5, 5], [5], [5]])
Output: [None, None, None, None, [7], []]
Hints
Hint 1
A single mapping from each user to the users they follow makes get_followers require scanning everyone. Think about what second view you need.
Hint 2
Store two dictionaries of sets: one for outgoing edges and one for incoming edges. Sets give constant-time insert, delete, and membership checks and make repeated follows harmless.
Hint 3
Every change must update both dictionaries together, and unfollow should only touch them if the edge actually exists. Use .get with an empty default for lookups so unknown users return [] or False, and sort only when returning lists.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A follow relationship is a directed edge, and the queries need both directions: get_following needs a user's outgoing edges and get_followers needs their incoming edges. Keeping only one direction would force a scan over all users to answer the other, so we maintain two dictionaries:
out_edges[u]: the set of users thatufollows.in_edges[v]: the set of users that followv.
Sets are used instead of lists because insertion, deletion, and membership testing are all O(1) on average. Insertion into a set also makes a repeated follow naturally idempotent.
Operations
- follow(a, b): create the sets lazily with
setdefault, addbtoout_edges[a]andatoin_edges[b]. - unfollow(a, b): first check that the edge exists. If it does not, do nothing. Otherwise remove it from both dictionaries, and delete any set that becomes empty so memory stays proportional to the live edges.
- get_following / get_followers: return the sorted contents of the relevant set, or an empty list for unknown users.
- is_following(a, b): a set membership test, defaulting to an empty set for unknown users.
Why it is correct
The invariant is that b is in out_edges[a] exactly when a is in in_edges[b]. follow inserts into both, unfollow removes from both and only after confirming the edge exists, and no other operation changes state. So both views always describe the same edge set. Self-follows need no special handling: the edge (u, u) simply lives in both maps for u. Sorting at read time gives the required deterministic ascending output.
Complexity
Let k be the size of a returned list, E the number of edges, and U the number of users with at least one edge.
follow,unfollow,is_following: O(1) average.get_following,get_followers: O(k log k) due to sorting.- Space: O(U + E), since each edge is stored twice.
Reference solution
from typing import List
def run_follow_graph_ops(operations: List[str], arguments: List[List[int]]) -> List[object]:
out_edges = {} # user -> set of users they follow
in_edges = {} # user -> set of users who follow them
results = []
for op, args in zip(operations, arguments):
if op == "follow":
a, b = args
out_edges.setdefault(a, set()).add(b)
in_edges.setdefault(b, set()).add(a)
results.append(None)
elif op == "unfollow":
a, b = args
targets = out_edges.get(a)
if targets is not None and b in targets:
targets.remove(b)
if not targets:
del out_edges[a]
sources = in_edges[b]
sources.remove(a)
if not sources:
del in_edges[b]
results.append(None)
elif op == "get_following":
results.append(sorted(out_edges.get(args[0], set())))
elif op == "get_followers":
results.append(sorted(in_edges.get(args[0], set())))
elif op == "is_following":
a, b = args
results.append(b in out_edges.get(a, set()))
return results