Dynamic Customer Payment Network Queries
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an in-memory query engine that records undirected peer-to-peer payment links between customer accounts over time and answers connectivity and hop-bounded neighborhood queries at any moment.
Every customer is identified by a non-empty string. Whenever customer x and customer y complete a payment, an undirected (two-way) direct link is established between them. Links accumulate over time and are never removed.
Implement transaction_network_queries(operations: List[str], arguments: List[List]) -> List, which starts from an empty graph, processes operations[i] with arguments[i] in order, and returns a list containing each step's result:
"addTransaction"with[x, y]: Records a symmetric direct payment link betweenxandyand producesNone. Recording an existing pair again (in either order) leaves connectivity unchanged, and self-links (x == y) never make a customer their own neighbor."haveEverTransactedTogether"with[x, y]: ReturnsTrueifxandybelong to the same connected component under all transactions recorded up to that step (connected directly or via a chain of intermediate partners), andFalseotherwise. If eitherxoryhas not yet appeared in any transaction, returnFalse."findNetwork"with[person]or[person, n]:- Unbounded (
[person]): Returns a lexicographically sortedList[str]of every customer reachable frompersonacross one or more transaction hops (the rest ofperson's connected component), excludingperson. - Hop-limited (
[person, n]): Returns a lexicographically sortedList[str]of every customer whose shortest-path hop distance frompersonis at least1and at mostn(1= direct partner,2= partner of a partner, etc.), excludingperson. - If
personhas never transacted, has no reachable neighbors within the limit, orn <= 0, return[].
- Unbounded (
Examples
Example 1
Input:
operations = ["haveEverTransactedTogether", "addTransaction", "addTransaction", "haveEverTransactedTogether", "addTransaction", "haveEverTransactedTogether"]
arguments = [["Ada", "Bo"], ["Ada", "Bo"], ["Cy", "Di"], ["Ada", "Di"], ["Bo", "Cy"], ["Di", "Ada"]]
Output: [False, None, None, False, None, True]
Initially no payments exist (False). After recording Ada-Bo and Cy-Di, the two pairs sit in separate components, so ("Ada", "Di") returns False. Recording Bo-Cy bridges the components into Ada-Bo-Cy-Di, so ("Di", "Ada") returns True.
Example 2
Input:
operations = ["addTransaction", "addTransaction", "addTransaction", "addTransaction", "findNetwork", "findNetwork", "findNetwork"]
arguments = [["u1", "u2"], ["u2", "u3"], ["u1", "u4"], ["u5", "u6"], ["u1"], ["u1", 1], ["u6"]]
Output: [None, None, None, None, ["u2", "u3", "u4"], ["u2", "u4"], ["u5"]]
The graph has two components: u4-u1-u2-u3 and u5-u6. findNetwork("u1") returns all three other members of "u1"'s component (["u2", "u3", "u4"]), whereas findNetwork("u1", 1) restricts to 1-hop direct partners (["u2", "u4"]), and findNetwork("u6") returns ["u5"].
Example 3
Input:
operations = ["addTransaction", "addTransaction", "addTransaction", "addTransaction", "addTransaction", "findNetwork", "findNetwork", "findNetwork"]
arguments = [["k1", "k2"], ["k2", "k3"], ["k3", "k4"], ["k4", "k5"], ["k5", "k1"], ["k1", 1], ["k1", 2], ["k1"]]
Output: [None, None, None, None, None, ["k2", "k5"], ["k2", "k3", "k4", "k5"], ["k2", "k3", "k4", "k5"]]
The five accounts form a cycle k1-k2-k3-k4-k5-k1. From "k1", "k2" and "k5" sit at hop 1, while "k3" and "k4" sit at hop 2, and the cycle never causes "k1" or already-visited accounts to be duplicated.
Example 4
Input:
operations = ["addTransaction", "addTransaction", "addTransaction", "addTransaction", "addTransaction", "addTransaction", "findNetwork", "findNetwork", "findNetwork"]
arguments = [["m1", "m2"], ["m2", "m3"], ["m3", "m4"], ["m2", "m5"], ["m4", "m5"], ["m5", "m6"], ["m3", 2], ["m6", 2], ["m9", 2]]
Output: [None, None, None, None, None, None, ["m1", "m2", "m4", "m5"], ["m2", "m4", "m5"], []]
From "m3", hop 1 reaches "m2" and "m4", and hop 2 reaches "m1" and "m5" ("m6" is 3 hops away and excluded). From "m6", hop 1 reaches "m5" and hop 2 reaches "m2" and "m4". Account "m9" has never transacted, so its network is [].
Constraints
0 <= len(operations) == len(arguments) <= 10^4- Customer identifiers are non-empty strings.
- Graphs may contain cycles, disconnected components, repeated edges, and long chains (up to thousands of hops).
- Every
findNetworkresult must be sorted in ascending lexicographical order.
Step-by-step walkthrough
Understand the problem and operations
Each customer account is identified by a string such as
"Ada"or"m1". Whenever two customers complete a payment, we add an undirected edge (a two-way link) between them. Edges are only added over time; they are never removed.We need to execute three kinds of operations at any point in the stream:
addTransaction(x, y)records a two-way payment link betweenxandyand returnsNone.haveEverTransactedTogether(x, y)returnsTrueifxandybelong to the same connected component (meaning a chain of one or more recorded payments connectsxtoy), andFalseotherwise.findNetwork(person)orfindNetwork(person, n)returns everyone reachable fromperson(or within at mostnhops whennis supplied), excludingperson, as an alphabetically sorted list of strings.
Two boundary rules apply immediately:
- Any customer who has never appeared in a recorded payment is connected to nobody (
False) and has an empty network ([]). - Calling
findNetworkwith a single argument means there is no hop ceiling (n = None).
Why we combine two data structures
The most natural way to represent the graph is an adjacency map: a dictionary mapping each customer to a
setof their direct 1-hop payment partners. From that map, we can run a breadth-first search (BFS)—exploring 1-hop partners, then 2-hop partners, and so on—to answer neighborhood queries.BFS is ideal for
findNetwork(person, n)because we have to visit and list every reachable account withinnhops anyway. Running a full BFS just to answerhaveEverTransactedTogether(x, y), however, wastes huge work: ifx's component has 50,000 accounts andyis outside it, BFS scans all 50,000 accounts just to returnFalse.Because transactions are append-only, components only ever merge. That matches Union-Find (Disjoint Set Union), which tracks component leaders in nearly
O(1)time per operation. Maintaining both structures side by side lets every query use the ideal tool:Transactions recorded: (Ada, Bo), (Bo, Cy) 1. Adjacency sets (stores exact 1-hop links for findNetwork): Ada -> {Bo} Bo -> {Ada, Cy} Cy -> {Bo} 2. Union-Find forest (tracks component roots for haveEverTransactedTogether): Ada <---- Bo <---- Cy (all share leader "Ada" -> same component!)Track components with Union-Find
In Union-Find, each registered customer has a
parentpointer. A customer pointing to themself (parent[r] == r) is the root (leader) of their component, and two customers share a component if and only if they have the same root.To keep trees flat across thousands of accounts—without recursion that could hit Python's stack limit—we combine two standard techniques using
whileloops:- Path compression in
_find: after walking up to locateroot, walk the same path a second time and point every visited node straight toroot. - Union by size in
add_transaction: when uniting two distinct roots, attach the smaller tree's root beneath the larger tree's root and sum their sizes.
Before _find("d"): After path compression: a (root) a (root) ^ / | \ | b c d b <-- c <-- dclass Transactions: def __init__(self): # partners: adjacency map {customer_id: set_of_direct_partners}, e.g. {"Ada": {"Bo"}} self.partners: Dict[str, Set[str]] = {} # parent: union-find parent link {customer_id: parent_id}; roots point to themselves self.parent: Dict[str, str] = {} # size: number of customers in each root's connected component, e.g. {"Ada": 3} self.size: Dict[str, int] = {} def _add_customer(self, person: str) -> None: # Register a first-time customer as an isolated component of size 1. if person not in self.partners: self.partners[person] = set() self.parent[person] = person self.size[person] = 1 def _find(self, person: str) -> str: # Phase 1: walk parent pointers upward until we reach the component root. root = person while self.parent[root] != root: root = self.parent[root] # Phase 2 (path compression): point every visited node directly to the root # so future lookups on these customers finish in one hop. while self.parent[person] != root: next_person = self.parent[person] self.parent[person] = root person = next_person return root def add_transaction(self, x: str, y: str) -> None: self._add_customer(x) self._add_customer(y) # Ignore self-links so a customer never appears as their own partner. if x == y: return # Record the undirected direct transaction edge in both partner sets. self.partners[x].add(y) self.partners[y].add(x) # Merge the two connected components if they are not already united. root_x = self._find(x) root_y = self._find(y) if root_x == root_y: return # Union by size: attach the smaller tree under the larger tree's root # so the tree height stays logarithmic even before path compression. if self.size[root_x] < self.size[root_y]: root_x, root_y = root_y, root_x self.parent[root_y] = root_x self.size[root_x] += self.size[root_y]- Path compression in
Answer connectivity queries
If either
xoryhas never appeared in a transaction, they are absent fromself.parent, so they cannot belong to the same component. Checking membership upfront prevents aKeyError; otherwise we simply compare_find(x)and_find(y).def have_ever_transacted_together(self, x: str, y: str) -> bool: # Anyone who has never appeared in a transaction has no connections yet. if x not in self.parent or y not in self.parent: return False return self._find(x) == self._find(y)Find the network within n hops using BFS
Why must we use breadth-first search (BFS) rather than depth-first search (DFS) when a hop limit
nis supplied? Inside a cyclic graph, DFS can wander along a 4-hop detour first, mark a node visited at depth 4, and skip expanding it later when a 2-hop shortcut arrives.BFS uses a first-in, first-out queue (
collections.deque) seeded withpersonat distance0. Because it processes all distance-dnodes before any distance-d + 1nodes, the very first time an account entersdistanceis guaranteed to record its true shortest-path hop distance:distancestores{customer_id: shortest_hops_from_person}and doubles as the visited set so cycles never loop infinitely.- Whenever
n is not None and distance[current] >= n, we skipcurrent's partners since they would lie atn + 1hops (using>=also handlesn <= 0cleanly). - Afterward,
del distance[person]excludes the starting customer andsorted(distance.keys())orders the result alphabetically.
def find_network(self, person: str, n: Optional[int] = None) -> List[str]: if person not in self.partners: return [] # distance: {customer_id: shortest_hop_count_from_person}, also serving as the visited set. distance: Dict[str, int] = {person: 0} queue = deque([person]) while queue: current = queue.popleft() # Do not expand neighbors once we reach the hop limit n (also handles n <= 0 safely). if n is not None and distance[current] >= n: continue for partner in self.partners[current]: if partner not in distance: distance[partner] = distance[current] + 1 queue.append(partner) # Exclude the starting customer from their own network and sort names alphabetically. del distance[person] return sorted(distance.keys())Dispatch operations and trace Example 4
transaction_network_queriesinstantiates a singleTransactionsobject and dispatches each command in order, forwardingargs[1]as the hop limit whenever a second argument is present:def transaction_network_queries(operations: List[str], arguments: List[List]) -> List: network = Transactions() results = [] # Dispatch each recorded command in sequence and collect its return value. for op, args in zip(operations, arguments): if op == "addTransaction": network.add_transaction(args[0], args[1]) results.append(None) elif op == "haveEverTransactedTogether": results.append(network.have_ever_transacted_together(args[0], args[1])) elif op == "findNetwork": if len(args) > 1: results.append(network.find_network(args[0], args[1])) else: results.append(network.find_network(args[0])) else: raise ValueError(f"unknown operation: {op}") return resultsLet's trace
findNetwork("m3", 2)on Example 4, where the recorded links arem1-m2, m2-m3, m3-m4, m2-m5, m4-m5, m5-m6:Graph layout: m1 - m2 - m3 - m4 \ / +--m5--+ | m6 Queue & distance trace for find_network("m3", 2): Start: queue = [m3], distance = {m3: 0} Pop m3 (dist 0 < 2): enqueue m2, m4 distance = {m3: 0, m2: 1, m4: 1} Pop m2 (dist 1 < 2): enqueue m1, m5 distance = {m3: 0, m2: 1, m4: 1, m1: 2, m5: 2} Pop m4 (dist 1 < 2): m3, m5 already seen distance unchanged Pop m1 (dist 2 >= 2): at hop limit -> skip partners Pop m5 (dist 2 >= 2): at hop limit -> skip partners (m6 at dist 3 stays excluded!) Remove m3 and sort keys -> ["m1", "m2", "m4", "m5"]Finally, Example 4 calls
findNetwork("m9", 2). Because"m9"never appeared in any recorded transaction,"m9" not in self.partnersreturns[]right away.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque class Transactions: def __init__(self): # partners: adjacency map {customer_id: set_of_direct_partners}, e.g. {"Ada": {"Bo"}} self.partners: Dict[str, Set[str]] = {} # parent: union-find parent link {customer_id: parent_id}; roots point to themselves self.parent: Dict[str, str] = {} # size: number of customers in each root's connected component, e.g. {"Ada": 3} self.size: Dict[str, int] = {} def _add_customer(self, person: str) -> None: # Register a first-time customer as an isolated component of size 1. if person not in self.partners: self.partners[person] = set() self.parent[person] = person self.size[person] = 1 def _find(self, person: str) -> str: # Phase 1: walk parent pointers upward until we reach the component root. root = person while self.parent[root] != root: root = self.parent[root] # Phase 2 (path compression): point every visited node directly to the root # so future lookups on these customers finish in one hop. while self.parent[person] != root: next_person = self.parent[person] self.parent[person] = root person = next_person return root def add_transaction(self, x: str, y: str) -> None: self._add_customer(x) self._add_customer(y) # Ignore self-links so a customer never appears as their own partner. if x == y: return # Record the undirected direct transaction edge in both partner sets. self.partners[x].add(y) self.partners[y].add(x) # Merge the two connected components if they are not already united. root_x = self._find(x) root_y = self._find(y) if root_x == root_y: return # Union by size: attach the smaller tree under the larger tree's root # so the tree height stays logarithmic even before path compression. if self.size[root_x] < self.size[root_y]: root_x, root_y = root_y, root_x self.parent[root_y] = root_x self.size[root_x] += self.size[root_y] def have_ever_transacted_together(self, x: str, y: str) -> bool: # Anyone who has never appeared in a transaction has no connections yet. if x not in self.parent or y not in self.parent: return False return self._find(x) == self._find(y) def find_network(self, person: str, n: Optional[int] = None) -> List[str]: if person not in self.partners: return [] # distance: {customer_id: shortest_hop_count_from_person}, also serving as the visited set. # Breadth-first search visits customers in non-decreasing hop order, so the first time # we reach any customer is guaranteed to be along a shortest path. distance: Dict[str, int] = {person: 0} queue = deque([person]) while queue: current = queue.popleft() # Do not expand neighbors once we reach the hop limit n (also handles n <= 0 safely). if n is not None and distance[current] >= n: continue for partner in self.partners[current]: if partner not in distance: distance[partner] = distance[current] + 1 queue.append(partner) # Exclude the starting customer from their own network and sort names alphabetically. del distance[person] return sorted(distance.keys()) def transaction_network_queries(operations: List[str], arguments: List[List]) -> List: network = Transactions() results = [] # Dispatch each recorded command in sequence and collect its return value. for op, args in zip(operations, arguments): if op == "addTransaction": network.add_transaction(args[0], args[1]) results.append(None) elif op == "haveEverTransactedTogether": results.append(network.have_ever_transacted_together(args[0], args[1])) elif op == "findNetwork": if len(args) > 1: results.append(network.find_network(args[0], args[1])) else: results.append(network.find_network(args[0])) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture customer accounts as attendees at a trade fair where every payment is a two-way handshake. We have to answer two distinct kinds of questions: "Do Ada and Di belong to the same connected cluster?" and "Which accounts lie within 2 handshakes of Ada?" Because no single structure handles both optimally, we maintain two synchronized views of the payment graph:
- A Union-Find (or disjoint-set) forest, which partitions accounts into non-overlapping groups with a single leader per group so membership in the same cluster can be tested in nearly constant time.
- An adjacency list, a dictionary mapping each account to its
setof direct 1-hop partners, traversed ring by ring via breadth-first search (BFS)—an algorithm that visits every 1-hop neighbor before any 2-hop neighbor, and so on.
Using graph search alone for haveEverTransactedTogether(x, y) could walk tens of thousands of accounts across x's component just to return False. Conversely, Union-Find compresses parent pointers directly toward component leaders, erasing exact hop counts needed by findNetwork(person, n). Using depth-first search (DFS)—plunging down one branch before backtracking—for hop-limited queries also breaks on cycles, since DFS can visit a neighbor along a 4-hop detour first, mark it visited, and ignore a valid 2-hop shortcut later.
Walk through Example 1 (Ada, Bo, Cy, Di):
- Initially
haveEverTransactedTogether("Ada", "Bo")sees neither name inparentand returnsFalse. addTransaction("Ada", "Bo")andaddTransaction("Cy", "Di")form two separate 2-person clusters ({"Ada", "Bo"}under"Ada"and{"Cy", "Di"}under"Cy"), sohaveEverTransactedTogether("Ada", "Di")compares different leaders and returnsFalse.addTransaction("Bo", "Cy")adds theBo-Cyedge inpartnersand unites"Cy"'s cluster under"Ada".- Now
haveEverTransactedTogether("Di", "Ada")finds the shared leader"Ada"in one hop and returnsTruewithout scanning edges, whilefindNetwork("Ada", 1)runs BFS from"Ada"(hop 0), discovers"Bo"(hop 1), stops at hop limit1before"Cy"(hop 2), and returns["Bo"].
Complexity
Let V be the number of unique customers registered so far, E be the number of unique transacting pairs, m be the number of edges incident to customers at distance < n during a findNetwork call, and k be the number of accounts returned by findNetwork (treating customer ID string lengths as bounded constants):
addTransactiontime —O(alpha(V))amortized: Inserting into both partnersets takesO(1)average hash-set time, and uniting roots in Union-Find with path compression (pointing visited nodes straight to the root) and union by size (attaching the smaller tree under the larger root) runs inO(alpha(V))amortized time (average cost per call across any sequence of operations), wherealphais the inverse Ackermann function—growing so slowly it never exceeds4for any in-memory input.haveEverTransactedTogethertime —O(alpha(V))amortized: Performs two dictionary membership checks and at most two_findroot lookups without traversing edges.findNetwork(person, n)time —O(1 + m + k log k): BFS pops only accounts within distancen, inspects partner sets only for accounts strictly closer thann(medge checks), and sorts thekdiscovered account IDs inO(k log k)time (O(V + E + V log V)worst-case whennis omitted).- Space —
O(V + E)persistent, plusO(k + 1)transient per network query:parentandsizestore one entry per customer (O(V)), andpartnersstores each undirected edge twice (O(E)). DuringfindNetwork,distanceandqueueholdpersonpluskdiscovered accounts.
Edge cases
- Unseen accounts: Querying
haveEverTransactedTogetherorfindNetworkon an account with zero recorded payments returnsFalseor[]without raisingKeyError(such as"m9"in Example 4). - Queries on an empty network: Both data structures start empty, returning
False(Example 1) or[]. - Transitive connectivity:
Ada-Bo,Cy-Di, andBo-Cyconnect"Di"and"Ada"across three hops even though they never transacted directly. - Repeated or reversed payments: Calling
addTransaction("u1", "u2")thenaddTransaction("u2", "u1")is idempotent—set.adddeduplicates partners androot_x == root_yskips double-addingsize. - Cyclic graphs: In the 5-cycle
k1-k2-k3-k4-k5-k1(Example 3), recording accounts indistancewhen enqueued prevents infinite loops and keeps"k1"out of its own network. - Zero or negative hop limit (
n <= 0): Becausedistance[person]starts at0,distance[current] >= nskips neighbor expansion immediately and returns[]. - Deep linear chains: Iterative
whileloops in both_findand BFS avoid Python'sRecursionErroron chains of thousands of accounts.
Common mistakes
- Using depth-limited DFS with a visited set for
findNetwork(person, n): On a cycle with branches, DFS can visit an account via a long route first, mark it visited beyond or at the hop limit, and fail to explore its neighbors along a shorter route. - Recording directed instead of undirected links: Updating
partners[x].add(y)while forgettingpartners[y].add(x)causesfindNetwork(y)to missx. - Testing
y in self.partners[x]forhaveEverTransactedTogether: Checks only 1-hop direct partners rather than multi-hop component reachability. - Leaving
personinside the returned network:personmust start indistanceat hop0so cycles cannot re-enqueue the origin, so forgettingdel distance[person]includespersonin their own output. - Returning an unsorted list or
set: Set iteration order varies with hash seeds, whereas the judge expects a sortedList[str]. - Skipping union by size: Attaching roots arbitrarily can create
O(V)-deep parent chains prior to path compression.
Alternative approaches
- Adjacency map + BFS only (omitting Union-Find): Store only
self.partnersand run BFS forhaveEverTransactedTogether(x, y)as well, returningTrueearly ifyis reached. That saves a few lines of state when connectivity checks are infrequent, at the cost ofO(V + E)worst-case scans per connectivity query. - Maintaining component member lists at Union-Find roots: Keep a member list on each root and merge the smaller list into the larger root on union (each account moves at most
O(log V)times total). UnboundedfindNetwork(person)calls then run inO(k log k)without edge traversal, thoughpartnersand BFS remain necessary whenever a hop limitnis given.
Follow-up questions
- How would the data structures change if recorded transactions could later be canceled or reversed? Standard Union-Find supports merges only and cannot split a component when an edge is deleted (especially when an alternate path still connects the endpoints). First, replace each partner
setwith a pair multiplicity map (Dict[str, int]) so reversing one payment only removes the undirected link when the pair's active count reaches zero. Once links can genuinely disappear, drop Union-Find and run bidirectional BFS (expanding frontiers fromxandysimultaneously, always advancing the smaller frontier) for connectivity checks, or rebuild Union-Find lazily after batches of deletions. - What bottlenecks arise when scaling multi-hop neighborhood queries to hundreds of millions of accounts, and how would you address high-degree merchant hubs? Union-Find state (
parentandsize) uses just two scalars per account and partitions cleanly in memory. The main bottleneck forfindNetwork(person, n)is high-degree hub accounts (such as a major retailer or transit agency with millions of customers), where a 2-hop query through one merchant explodes to millions of accounts. Production payment graphs mitigate hub explosion by enforcing per-node degree caps during neighborhood expansion, separating merchant edges from peer-to-peer edges, and sharding adjacency lists across workers with hop-by-hop frontier batching. - How would you extend the breadth-first search to return an explicit minimum-hop transaction chain between two connected customers? Because BFS discovers every account along a shortest path, store
predecessor[partner] = currentinside theif partner not in distance:block the moment each account is first discovered. Stop early as soon as the target account is enqueued, walkpredecessorpointers backward from target to source, and reverse the collected list to produce a minimum-hop chain.
Follow-up questions
- How would the data structures change if recorded transactions could later be canceled or reversed?
- What bottlenecks arise when scaling multi-hop neighborhood queries to hundreds of millions of accounts, and how would you address high-degree merchant hubs?
- How would you extend the breadth-first search to return an explicit minimum-hop transaction chain between two connected customers?
Similar questions
- Card Prefix Attribute Store with Trust Priority
- Find Valid 2x2 Subgrids Containing Each Marked Cell
- Walking Through a Production Project With Defensible AI Use
- Driving a High-Impact Migration Across Legacy and Regulated Systems
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger