Support updates and count target-sum pairs
Company: Capital One
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Take-home Project
Quick Answer: This question evaluates data structures and algorithmic skills for dynamic pair counting, focusing on frequency management, efficient update handling, and query-time computation in a two-sum variant.
Constraints
- 1 <= len(A), len(B) <= 10^5
- Number of operations up to 10^5
- Values can be negative and span the 32-bit integer range
- For an update, 0 <= index < len(B)
- Pairs are counted with multiplicity (by index combination, not by distinct value)
Examples
Input: ([1, 2, 2], [3, 2], [("count", 4)])
Expected Output: [3]
Explanation: Worked example: A[0]=1 pairs with B[0]=3; A[1]=2 and A[2]=2 each pair with B[1]=2 → 3 pairs.
Input: ([1, 2, 2], [3, 2], [("count", 4), ("update", 1, 3), ("count", 4)])
Expected Output: [3, 2]
Explanation: After setting B[1]=3, B=[3,3]; only A[0]=1 sums to 4 with each 3, giving 2 pairs.
Input: ([5], [5], [("count", 10), ("update", 0, 0), ("count", 10), ("count", 5)])
Expected Output: [1, 0, 1]
Explanation: 5+5=10 (1 pair); after B[0]=0 nothing sums to 10; 5+0=5 gives 1 pair.
Input: ([1, 1, 1], [1, 1], [("count", 2)])
Expected Output: [6]
Explanation: Every A[i]=1 pairs with every B[j]=1: 3*2=6 pairs (multiplicity).
Input: ([-3, 2], [3, -2], [("count", 0), ("count", 100)])
Expected Output: [2, 0]
Explanation: Negatives: -3+3=0 and 2+(-2)=0 give 2 pairs; nothing reaches 100.
Input: ([0], [0], [("count", 0)])
Expected Output: [1]
Explanation: Single zero in each array sums to 0 → 1 pair.
Input: ([1, 2, 3], [4, 5, 6], [("update", 0, 2), ("update", 1, 2), ("update", 2, 2), ("count", 4)])
Expected Output: [3]
Explanation: After three updates B=[2,2,2]; only A[0]=1 reaches 4 with each 2 → wait, 1+2=3 not 4. A[1]=2 pairs with none? 2+2=4 holds for A[1] across all three B values → 3 pairs.
Hints
- A plain presence-based dictionary two-sum undercounts when values repeat. Count occurrences (frequencies) instead.
- Keep a frequency map of B's current values so each count query is sum over i of freq[target - A[i]].
- An update is O(1): decrement the old value's frequency, increment the new value's, and remember to mutate B itself.
- Iterate A (the fixed array) for each query; updates only touch B, so the map of B stays cheap to maintain.