Live Complement Counting with Point Updates on One Array
Data Structure DesignAuto-graded · 19 test casesLast updated
Answer repeated target-sum pair-count queries over two integer arrays while the second array receives point updates, using frequency maps.
You have two integer arrays, a (never changes) and b (can change), plus a sequence of operations to process in order. Operations are given as two parallel lists: op_names[k] is the name of the k-th operation and op_args[k] holds its arguments.
There are two kinds of operations:
"Query"withop_args[k] = [target]: count the index pairs(i, j)wherea[i] + b[j] == target, using the current contents ofb."Replace"withop_args[k] = [index, value]: assignb[index] = value. This produces no output.
Return a list with one integer for each "Query" operation, in the order the queries appear.
Details
- Pairs are counted by position, so equal values at different positions count as different pairs. For example, if
a = [1, 1, 2]andb = [2, 2], then a target of3matches 2 pairs from the two1s with2s inb, each pair counted separately, giving 4 in total. - A
"Replace"that writes the value already stored at that index changes nothing. - If there are no matching pairs, the answer to that query is
0. - Every
"Replace"index is a valid position inb. - The inputs may be very large, so recomputing all
len(a) * len(b)pairs for every query is too slow. Aim for cheap updates and queries that do not scale with the full array lengths.
Constraints
0 <= len(a), len(b) <= 10^5len(op_names) == len(op_args), at most10^5operations- Values in
a,b, replacement values, and targets are integers that may be negative - Operation names are exactly
"Query"or"Replace" - Query counts can be large (up to about
10^10), so use an integer type that will not overflow
Examples
Example 1
Input: count_pair_sums_with_updates([1, 3], [2, 4], ['Query', 'Replace', 'Query'], [[5], [0, 3], [4]])
Output: [2, 1]
Example 2
Input: count_pair_sums_with_updates([1, 1, 2], [2, 2], ['Query', 'Replace', 'Query', 'Replace', 'Query'], [[3], [1, 3], [4], [0, 2], [3]])
Output: [4, 3, 2]
Hints
Hint 1
Two index pairs are interchangeable if they use the same pair of values. Think about counting how many times each value occurs rather than looking at positions.
Hint 2
For a fixed target, the answer is the sum over each distinct value v in a of (occurrences of v in a) times (occurrences of target - v in b).
Hint 3
Keep a frequency map of b and also the array b itself, so a replacement knows which old value to decrement. Remove keys whose count reaches zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Pairs with the same value combination behave identically, so group by value. If count_a[x] is how many times x appears in a and count_b[y] is how many times y appears in b, then exactly count_a[x] * count_b[y] index pairs have values (x, y). A query for target is therefore
sum over distinct x in a of count_a[x] * count_b[target - x]
We maintain:
a_counts: a frequency map ofa, built once.b_counts: a frequency map ofb, kept current after each replacement.current_b: a copy ofb, so a replacement can find the old value at an index.
Replace(index, value): look up old = current_b[index]. If it equals value, nothing to do. Otherwise decrement b_counts[old] (deleting the key at zero), increment b_counts[value], and write current_b[index] = value. This is O(1).
Query(target): iterate over the smaller of the two frequency maps and look up the complement target - value in the other. The product sum is symmetric, so the choice of side does not change the answer, only the cost.
Why it is correct
Every index pair (i, j) has exactly one value pair (a[i], b[j]), and it contributes to target exactly when b[j] = target - a[i]. Summing count_a[x] * count_b[target - x] over all distinct x counts each qualifying index pair once. Each replacement removes one occurrence of the old value and adds one of the new value, so b_counts always matches the current b at query time. Deleting zero-count keys keeps the map sizes equal to the number of distinct values, and it does not affect correctness since missing keys are treated as 0.
Complexity
Let n = len(a), m = len(b), q = number of operations, and dA, dB the numbers of distinct values.
- Build: O(n + m).
- Replace: O(1) expected.
- Query: O(min(dA, dB)) expected.
- Total time: O(n + m + q * min(dA, dB)).
- Space: O(n + m), plus O(q) for the output.
Reference solution
from collections import Counter
from typing import List
def count_pair_sums_with_updates(a: List[int], b: List[int], op_names: List[str], op_args: List[List[int]]) -> List[int]:
a_counts = Counter(a)
b_counts = Counter(b)
current_b = list(b)
results = []
for name, args in zip(op_names, op_args):
if name == "Query":
target = args[0]
small, large = a_counts, b_counts
if len(small) > len(large):
small, large = large, small
total = 0
for value, count in small.items():
other = large.get(target - value, 0)
if other:
total += count * other
results.append(total)
else:
index, value = args
old_value = current_b[index]
if old_value == value:
continue
b_counts[old_value] -= 1
if b_counts[old_value] == 0:
del b_counts[old_value]
b_counts[value] += 1
current_b[index] = value
return results