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:

  1. "addTransaction" with [x, y]: Records a symmetric direct payment link between x and y and produces None. Recording an existing pair again (in either order) leaves connectivity unchanged, and self-links (x == y) never make a customer their own neighbor.
  2. "haveEverTransactedTogether" with [x, y]: Returns True if x and y belong to the same connected component under all transactions recorded up to that step (connected directly or via a chain of intermediate partners), and False otherwise. If either x or y has not yet appeared in any transaction, return False.
  3. "findNetwork" with [person] or [person, n]:
    • Unbounded ([person]): Returns a lexicographically sorted List[str] of every customer reachable from person across one or more transaction hops (the rest of person's connected component), excluding person.
    • Hop-limited ([person, n]): Returns a lexicographically sorted List[str] of every customer whose shortest-path hop distance from person is at least 1 and at most n (1 = direct partner, 2 = partner of a partner, etc.), excluding person.
    • If person has never transacted, has no reachable neighbors within the limit, or n <= 0, return [].

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 findNetwork result must be sorted in ascending lexicographical order.

Step-by-step walkthrough

  1. 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 between x and y and returns None.
    • haveEverTransactedTogether(x, y) returns True if x and y belong to the same connected component (meaning a chain of one or more recorded payments connects x to y), and False otherwise.
    • findNetwork(person) or findNetwork(person, n) returns everyone reachable from person (or within at most n hops when n is supplied), excluding person, 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 findNetwork with a single argument means there is no hop ceiling (n = None).
  2. 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 set of 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 within n hops anyway. Running a full BFS just to answer haveEverTransactedTogether(x, y), however, wastes huge work: if x's component has 50,000 accounts and y is outside it, BFS scans all 50,000 accounts just to return False.

    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!)
    
  3. Track components with Union-Find

    In Union-Find, each registered customer has a parent pointer. 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 while loops:

    1. Path compression in _find: after walking up to locate root, walk the same path a second time and point every visited node straight to root.
    2. 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 <-- d
    
    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]
    
  4. Answer connectivity queries

    If either x or y has never appeared in a transaction, they are absent from self.parent, so they cannot belong to the same component. Checking membership upfront prevents a KeyError; 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)
    
  5. 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 n is 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 with person at distance 0. Because it processes all distance-d nodes before any distance-d + 1 nodes, the very first time an account enters distance is guaranteed to record its true shortest-path hop distance:

    • distance stores {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 skip current's partners since they would lie at n + 1 hops (using >= also handles n <= 0 cleanly).
    • Afterward, del distance[person] excludes the starting customer and sorted(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())
    
  6. Dispatch operations and trace Example 4

    transaction_network_queries instantiates a single Transactions object and dispatches each command in order, forwarding args[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 results
    

    Let's trace findNetwork("m3", 2) on Example 4, where the recorded links are m1-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.partners returns [] right away.

  7. 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:

  1. 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.
  2. An adjacency list, a dictionary mapping each account to its set of 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):

  1. Initially haveEverTransactedTogether("Ada", "Bo") sees neither name in parent and returns False.
  2. addTransaction("Ada", "Bo") and addTransaction("Cy", "Di") form two separate 2-person clusters ({"Ada", "Bo"} under "Ada" and {"Cy", "Di"} under "Cy"), so haveEverTransactedTogether("Ada", "Di") compares different leaders and returns False.
  3. addTransaction("Bo", "Cy") adds the Bo-Cy edge in partners and unites "Cy"'s cluster under "Ada".
  4. Now haveEverTransactedTogether("Di", "Ada") finds the shared leader "Ada" in one hop and returns True without scanning edges, while findNetwork("Ada", 1) runs BFS from "Ada" (hop 0), discovers "Bo" (hop 1), stops at hop limit 1 before "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):

  • addTransaction time — O(alpha(V)) amortized: Inserting into both partner sets takes O(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 in O(alpha(V)) amortized time (average cost per call across any sequence of operations), where alpha is the inverse Ackermann function—growing so slowly it never exceeds 4 for any in-memory input.
  • haveEverTransactedTogether time — O(alpha(V)) amortized: Performs two dictionary membership checks and at most two _find root lookups without traversing edges.
  • findNetwork(person, n) time — O(1 + m + k log k): BFS pops only accounts within distance n, inspects partner sets only for accounts strictly closer than n (m edge checks), and sorts the k discovered account IDs in O(k log k) time (O(V + E + V log V) worst-case when n is omitted).
  • Space — O(V + E) persistent, plus O(k + 1) transient per network query: parent and size store one entry per customer (O(V)), and partners stores each undirected edge twice (O(E)). During findNetwork, distance and queue hold person plus k discovered accounts.

Edge cases

  • Unseen accounts: Querying haveEverTransactedTogether or findNetwork on an account with zero recorded payments returns False or [] without raising KeyError (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, and Bo-Cy connect "Di" and "Ada" across three hops even though they never transacted directly.
  • Repeated or reversed payments: Calling addTransaction("u1", "u2") then addTransaction("u2", "u1") is idempotent—set.add deduplicates partners and root_x == root_y skips double-adding size.
  • Cyclic graphs: In the 5-cycle k1-k2-k3-k4-k5-k1 (Example 3), recording accounts in distance when enqueued prevents infinite loops and keeps "k1" out of its own network.
  • Zero or negative hop limit (n <= 0): Because distance[person] starts at 0, distance[current] >= n skips neighbor expansion immediately and returns [].
  • Deep linear chains: Iterative while loops in both _find and BFS avoid Python's RecursionError on 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 forgetting partners[y].add(x) causes findNetwork(y) to miss x.
  • Testing y in self.partners[x] for haveEverTransactedTogether: Checks only 1-hop direct partners rather than multi-hop component reachability.
  • Leaving person inside the returned network: person must start in distance at hop 0 so cycles cannot re-enqueue the origin, so forgetting del distance[person] includes person in their own output.
  • Returning an unsorted list or set: Set iteration order varies with hash seeds, whereas the judge expects a sorted List[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.partners and run BFS for haveEverTransactedTogether(x, y) as well, returning True early if y is reached. That saves a few lines of state when connectivity checks are infrequent, at the cost of O(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). Unbounded findNetwork(person) calls then run in O(k log k) without edge traversal, though partners and BFS remain necessary whenever a hop limit n is 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 set with 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 from x and y simultaneously, 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 (parent and size) uses just two scalars per account and partitions cleanly in memory. The main bottleneck for findNetwork(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] = current inside the if partner not in distance: block the moment each account is first discovered. Stop early as soon as the target account is enqueued, walk predecessor pointers backward from target to source, and reverse the collected list to produce a minimum-hop chain.

Follow-up questions

Similar questions

More Square interview questions

All 5 Square questions →