← 返回 capitalone 的题目列表Dynamic Two-Array Pair Sum Queries
类型:qbank
Maintain arrays `a` and `b` under point updates to `a`. For each sum query, append the number of `(a[i], b[j])` pairs whose values add to the requested target.
Requirements
Input: arrays a and b, plus an ordered list of queries.
Query [0, x]: count combinations of one element from a and one element from b whose sum is x; append the count to the output array.
Query [1, z, y]: update a[z] to y.
Return the array of counts produced by all type-0 queries.
Pair multiplicity matters: equal values at different indices count as separate combinations.
Examples
a = [1, 2]
b = [2, 3, 4]
queries = [[0, 4], [1, 0, 3], [0, 4]]
Before update: pairs summing to 4 are (1, 3) and (2, 2), so append 2.
After setting a[0] = 3, a = [3, 2]; only (2, 2) sums to 4, so append 1.
Return [2, 1]
Notes
Keep frequency maps for both arrays. Type-0 query is sum(count_a[v] * count_b[x - v] for v in count_a). If a is the smaller map, iterate count_a; otherwise iterate the smaller of the two maps for speed.
Type-1 update must decrement the old a[z] count, delete the key at zero, assign a[z] = y, then increment count_a[y]. Forgetting to update the backing array makes the second update to the same index wrong.
The brute-force nested loop is easy to write but can time out. The hashmap version is the expected Q4-level fix.
Variants flip which of the two arrays receives the point updates; the frequency-map approach is symmetric, so pin down the updated array before coding.
If value ranges are small, a precomputed convolution-like table of pair sums can make queries O(1), but point updates then require updating all sums involving the changed value. For CodeSignal limits, the frequency-map trade-off is usually enough.
Preparation
Implement the frequency-map version and test duplicate values in both arrays.
Add two consecutive updates to the same index to verify the old count is removed correctly.
Practise explaining the complexity trade-off between iterating the smaller frequency map per query and maintaining a full sum-count table under updates.