Cluster Exposures: Net Change per Asset Group
Trees & GraphsModel answerLast updated
Find connected components in an asset correlation graph and return the summed position delta for each component as a labeled group.
Cluster Exposures
You are building a risk aggregation tool. The tool receives two inputs:
-
positions— a list of(ticker, delta)pairs, wheretickeris a string asset identifier anddeltais a signed integer representing the net change in that asset's holdings. The same ticker may appear more than once; treat repeated entries as additive. -
links— a list of(ticker_a, ticker_b)pairs indicating that the two assets belong to the same hedging cluster. The relationship is symmetric: if A is linked to B, then B is linked to A. Linkage is also transitive: if A–B and B–C, all three belong to the same cluster.
A ticker that appears in links but has no entry in positions is still a valid cluster member with a delta of zero. A ticker with no links at all forms a singleton cluster.
Your task: partition all tickers into their clusters and return a dictionary mapping a cluster label to the cluster's total delta.
The label for a cluster is the alphabetically sorted ticker names joined by _. For a singleton, the label is just the ticker name.
Function Signature
def cluster_deltas(
positions: List[Tuple[str, int]],
links: List[Tuple[str, str]],
) -> Dict[str, int]:
Constraints
- Number of distinct tickers: 1 to 10^5
- Number of links: 0 to 10^5
delta: −10^9 to 10^9
Examples
Example 1
positions = [('AAPL', 10), ('MSFT', -5), ('GOOG', 20)]
links = [('AAPL', 'MSFT')]
Output: {'AAPL_MSFT': 5, 'GOOG': 20}
AAPL and MSFT are in the same cluster: 10 + (−5) = 5. GOOG is unlinked, so it stands alone with delta 20.
Example 2
positions = [('A', 1), ('B', 2), ('C', 3)]
links = [('A', 'B'), ('B', 'C')]
Output: {'A_B_C': 6}
A–B and B–C make all three one cluster: 1 + 2 + 3 = 6.
What is expected
Return the dictionary described above. Order of keys does not matter. Explain your approach, its time and space complexity, and how you handle the edge cases listed below:
- A ticker that appears in
linksbut not inpositions. - Duplicate or reversed link entries.
- Very large chains of tickers (up to 10^5 nodes).
- Extremely large total deltas.
Hints
Hint 1
Model each ticker as a graph node and each link as an undirected edge. The clusters you need are exactly the connected components of that graph.
Hint 2
Before traversing, aggregate deltas per ticker into a hash map — a ticker can appear multiple times in `positions`. Also register any ticker that appears only in `links` with a default delta of zero, or you will miss nodes that bridge two groups.
Hint 3
Use iterative DFS (an explicit stack) rather than recursive DFS. A chain of 10^5 nodes will blow Python's default recursion limit. After collecting all members of a component, sort their names and join with `_` to get a deterministic key regardless of traversal order.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a connected-components problem. Each ticker is a node; each link is an undirected edge. A cluster is one connected component, and its delta is the sum of individual deltas inside it.
Steps
- Aggregate deltas. Walk through
positionsand accumulate each ticker's total delta in a hash map. Handles duplicates automatically. - Build an adjacency list. For every
(a, b)inlinks, addbtoa's neighbor list andatob's. - Register link-only tickers. Any ticker that appears in
linksbut not inpositionsgets a delta of 0. Skipping these nodes would merge into the wrong groups — a link-only ticker can bridge two otherwise separate clusters. - Iterative DFS. Iterate over every node. If unvisited, push it onto a stack and collect all reachable nodes. Sum their deltas.
- Build the key. Sort the member names lexicographically and join with
_. Sorting makes the key deterministic regardless of input order or traversal order — say this out loud in an interview.
Complexity
- V = distinct tickers, E = number of links
- Time: O(V + E) for aggregation and graph construction, O(V log V) for sorting component members. Total: O(V log V + E).
- Space: O(V + E) for the adjacency list, visited set, and output.
If sorting is dropped (e.g. the key format changes), time reduces to O(V + E).
Edge Cases
- No links. Every ticker is its own singleton. The loop starts a new DFS from every node and each component has exactly one member.
- Duplicate or reversed link entries like
('A','B')and('B','A'). Harmless — the visited set prevents revisiting a node, so no double-counting occurs. - Self-loops
('A','A'). Also harmless for the same reason. - Ticker in
linksbut not inpositions. Registered with delta 0. It still appears in the cluster key and may bridge other tickers. Omitting it would silently split a cluster. - Large chains. Recursive DFS hits Python's default limit (~1 000 frames) on a 10^5-node chain. Use an explicit stack.
- Large sums. Up to 10^5 × 10^9 = 10^14. Python integers handle this natively; in Java/C++ use
long.
Python Solution
from collections import defaultdict
from typing import Dict, List, Tuple
def cluster_deltas(
positions: List[Tuple[str, int]],
links: List[Tuple[str, str]],
) -> Dict[str, int]:
# Step 1: aggregate deltas per ticker.
delta: Dict[str, int] = defaultdict(int)
for ticker, amount in positions:
delta[ticker] += amount
# Step 2: build undirected adjacency list.
graph: Dict[str, List[str]] = defaultdict(list)
for a, b in links:
graph[a].append(b)
graph[b].append(a)
# Step 3: register tickers that only appear in links.
# We collect all nodes into one list to iterate over later.
all_nodes = list(delta.keys())
for a, b in links:
for ticker in (a, b):
if ticker not in delta:
delta[ticker] = 0
all_nodes.append(ticker)
# Step 4 & 5: iterative DFS, one component per unvisited start node.
visited: set = set()
result: Dict[str, int] = {}
for start in all_nodes:
if start in visited:
continue
# Collect every node in this component.
visited.add(start)
stack = [start]
members: List[str] = []
total = 0
while stack:
node = stack.pop()
members.append(node)
total += delta[node]
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
# Deterministic label: sorted names joined by '_'.
label = "_".join(sorted(members))
result[label] = total
return result
Tracing Example 1. Delta map: {AAPL: 10, MSFT: -5, GOOG: 20}. Edge: AAPL–MSFT.
- DFS from AAPL → visits MSFT. Members
['AAPL', 'MSFT'], sorted key'AAPL_MSFT', total 5. - DFS from GOOG → no neighbors. Key
'GOOG', total 20.
Output matches.
Alternative: Union-Find
Disjoint Set Union (DSU) with path compression and union-by-rank is a natural fit. After processing all links, iterate over nodes, find each node's root, and accumulate deltas per root. Runtime is O((V + E) · α(V)) — effectively linear. DSU is preferable when links arrive as a stream and you need running group totals; DFS is simpler when the full graph is known up front.
Common Mistakes
- Using recursive DFS on large inputs. Fails on deep chains; always use an explicit stack in Python.
- Ignoring link-only tickers. A node with no delta but present in
linksbridges components — dropping it silently merges the wrong groups. - Non-deterministic keys. Using discovery order or a set for member collection produces different keys on different runs. Sort the members.
- Not summing duplicate position entries. If
('AAPL', 10)and('AAPL', 5)both appear, AAPL's delta is 15, not whichever comes last.
Follow-up: Directed Links
If links were one-directional (A hedges B but not vice versa), "cluster" would need a precise definition. Weakly connected components (ignore direction) require no code change. Strongly connected components (mutual reachability) call for Tarjan's or Kosaraju's algorithm in O(V + E). If the question is about downstream exposure propagation, condense the graph into a DAG of SCCs and sum deltas in reverse topological order — but watch for diamond shapes that cause double-counting along parallel paths.