KatInterview

Live Complement Counting with Point Updates on One Array

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designhash-mapfrequency-countcounting-pairs

Last 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" with op_args[k] = [target]: count the index pairs (i, j) where a[i] + b[j] == target, using the current contents of b.
  • "Replace" with op_args[k] = [index, value]: assign b[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] and b = [2, 2], then a target of 3 matches 2 pairs from the two 1s with 2s in b, 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 in b.
  • 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^5
  • len(op_names) == len(op_args), at most 10^5 operations
  • 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.