Acyclic Invitation Graph with Depth Queries and Expected Payout
Trees & GraphsAuto-graded · 18 test casesLast updated
Simulate a stream of operations on a DAG: reject cycle-forming or duplicate edges, count nodes within a hop limit, and sum expected decayed payouts using BFS shortest distances.
Invitation Graph Simulator
A hiring platform records who invited whom. Each invitation is a directed link from an inviter to an invitee. To block fraudulent invitation loops, the set of links must never contain a directed cycle.
You are given two parallel lists, operations and arguments. Process them in order, starting from an empty graph, and return a list containing one result per operation.
Operations
Each operations[i] is one of the following names, and arguments[i] is the list of its parameters.
"add_referral" with arguments [referrer, referee]
- Try to add a directed link
referrer -> referee. - Both users are registered in the graph as known users (if not already known), even if the link is then rejected.
- Reject the link and return
Falseif any of these holds:referrer == referee;- the link already exists;
- adding the link would create a directed cycle (that is,
refereecan already reachreferrerthrough existing links).
- Otherwise store the link and return
True.
"get_reach" with arguments [user_id, max_depth]
- Return the number of distinct users, other than
user_iditself, that can be reached fromuser_idby following at mostmax_depthlinks. A user counts if its shortest-path distance fromuser_idis at mostmax_depth. - Return
0ifuser_idis unknown or ifmax_depth <= 0.
"expected_network_value" with arguments [user_id, base_value, prob, decay]
- Every user
vreachable fromuser_id(excludinguser_id), at shortest-path distanced >= 1, converts with probabilityprob. A converted user contributesbase_value * decay ** (d - 1). - Return the expected total contribution: the sum over all reachable users
vofprob * base_value * decay ** (d - 1). - Always use the shortest distance when several paths lead to the same user.
- Return
0(numerically zero) ifuser_idis unknown or has no reachable users. - Use Python's convention that
0.0 ** 0 == 1.0, so withdecay = 0only users at distance 1 contribute.
Output
Return a list of results in the same order as the operations: a boolean for add_referral, an integer for get_reach, and a number for expected_network_value.
Constraints
len(operations) == len(arguments).- User identifiers are non-empty alphanumeric strings.
0.0 <= prob <= 1.0,0.0 <= decay <= 1.0,base_value >= 0.0.max_depthmay be zero or negative, in which case the reach is0.- Operation names are always one of the three listed above.
- The number of users and operations is small enough that a graph traversal per operation is acceptable.
Examples
Example 1
Input: simulate_invitations(['add_referral', 'add_referral', 'add_referral', 'add_referral', 'add_referral', 'get_reach', 'get_reach', 'expected_network_value'], [['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'D'], ['D', 'A'], ['A', 1], ['A', 2], ['A', 100, 0.5, 0.5]])
Output: [True, True, True, True, False, 2, 3, 125]
Example 2
Input: simulate_invitations(['add_referral', 'add_referral', 'get_reach', 'expected_network_value'], [['Alice', 'Bob'], ['Alice', 'Bob'], ['Unknown', 5], ['Bob', 50, 0.8, 0.9]])
Output: [True, False, 0, 0]
Hints
Hint 1
Both the cycle check and the two queries need the same thing: hop distances from a starting user. Write one reusable traversal helper.
Hint 2
Adding u -> v closes a loop exactly when v can already reach u. Run a traversal from v and see whether u shows up. Handle self-links and duplicate links before that.
Hint 3
Use BFS so the first time a user is seen gives their shortest distance. For depth-limited reach, do not expand users whose distance already equals the limit; for the payout, add prob * base_value * decay ** (d - 1) for every user at distance d >= 1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep an adjacency map from each user to the set of users they directly invited. All three operations rely on a single helper: a BFS that returns the shortest hop distance from a start user to every user it can reach, optionally refusing to expand users that are already at a given depth.
add_referral(u, v): First register both users. Reject ifu == vor the link already exists (an O(1) set lookup). Otherwise run BFS fromv; ifuis among the reached users, the new link would close a cycle, so reject. If not, store the link.get_reach(u, k): Return0ifk <= 0oruis unknown. Otherwise run BFS fromu, not expanding users at distancek, and return the number of discovered users minus one (to excludeu).expected_network_value(u, B, p, g): Run a full BFS fromu. For each user at distanced >= 1, addp * B * g ** (d - 1).
Why it is correct
- Cycles. The graph is acyclic before each insertion. Any new cycle must use the new edge
u -> v, so it consists of that edge plus a pathv ~> u. Such a path exists exactly when BFS fromvreachesu. Self-links are the trivial cycle and are rejected directly. - Shortest distances. BFS discovers users in non-decreasing order of distance, so the distance recorded at first discovery is the shortest one. This is what makes diamond shapes (two paths to the same user) count once, with the shorter distance.
- Depth limit. Not expanding users at distance
kmeans every discovered user has distance at mostk, and every user with shortest distance at mostkis discovered. - Expected value. The expected payout of each user is
p * B * g ** (d - 1). By linearity of expectation, the total expectation is the sum of these terms, with no need to reason about joint probabilities.
Unknown users give an empty distance map, which yields 0 for both queries. Users are registered even when a link is rejected, which does not change any query result since they have no outgoing links.
Complexity
With V users and E links, each operation costs O(V + E) time in the worst case and O(V) extra space for the BFS. The graph itself uses O(V + E) space. Over Q operations the total time is O(Q * (V + E)).
Reference solution
from collections import deque
from typing import List
def simulate_invitations(operations: List[str], arguments: List[List]) -> List:
graph = {}
results = []
def distances(start, max_depth=None):
if start not in graph:
return {}
dist = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
if max_depth is not None and dist[node] >= max_depth:
continue
for neighbor in graph[node]:
if neighbor not in dist:
dist[neighbor] = dist[node] + 1
queue.append(neighbor)
return dist
for operation, args in zip(operations, arguments):
if operation == "add_referral":
referrer, referee = args
graph.setdefault(referrer, set())
graph.setdefault(referee, set())
if referee in graph[referrer] or referrer == referee:
results.append(False)
elif referrer in distances(referee):
results.append(False)
else:
graph[referrer].add(referee)
results.append(True)
elif operation == "get_reach":
user_id, max_depth = args
if max_depth <= 0 or user_id not in graph:
results.append(0)
else:
results.append(len(distances(user_id, max_depth)) - 1)
elif operation == "expected_network_value":
user_id, base_value, prob, decay = args
dist = distances(user_id)
results.append(sum(prob * base_value * (decay ** (depth - 1))
for node, depth in dist.items() if depth >= 1))
else:
raise ValueError("Unknown operation")
return results