Problem Description
We are given two integer arrays, nums1 and nums2. We need to design a data structure that supports two operations: (1) add a positive integer to an element at a specified index in nums2, and (2) count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given total.
Key Insights
- Precompute and maintain a frequency map (hash table) for the elements in nums2.
- Since nums1 is relatively small (at most 1000 elements), iterating through it for each count query is efficient.
- For each add query, update the frequency map in O(1) time by decrementing the frequency of the old value and incrementing that of the new value.
- For each count query, iterate through nums1 and use the frequency map to quickly find how many complementary values exist in nums2.
Space and Time Complexity
Time Complexity:
- add: O(1)
- count: O(n1) where n1 is the length of nums1
Space Complexity: O(n2) due to the frequency map for nums2
Solution
We use a hash table to maintain the frequency of each element in nums2. During initialization, we build this mapping. In the add method, we update the frequency map by first reducing the count for the current value at the given index, then updating the element, and finally incrementing the frequency for the new value. The count method iterates through nums1 and, for each element, calculates the needed complement such that the sum equals tot. The frequency map is then used to look up how many times this complement appears in nums2. This approach ensures that both operations are efficient given the problem constraints.