Problem
You are given two integer arrays nums1
and nums2
. You are tasked to implement a data structure that supports queries of two types:
- Add a positive integer to an element of a given index in the array
nums2
. - Count the number of pairs
(i, j)
such thatnums1[i] + nums2[j]
equals a given value (0 <= i < nums1.length
and0 <= j < nums2.length
).
Implement the FindSumPairs
class:
FindSumPairs(int[] nums1, int[] nums2)
Initializes theFindSumPairs
object with two integer arraysnums1
andnums2
.void add(int index, int val)
Addsval
tonums2[index]
, i.e., applynums2[index] += val
.int count(int tot)
Returns the number of pairs(i, j)
such thatnums1[i] + nums2[j] == tot
.
Examples
Example 1
|
|
Constraints
1 <= nums1.length <= 1000
1 <= nums2.length <= 10^5
1 <= nums1[i] <= 10^9
1 <= nums2[i] <= 10^5
0 <= index < nums2.length
1 <= val <= 10^5
1 <= tot <= 10^9
- At most
1000
calls are made toadd
andcount
each.
Solution
Method 1 – Hash Map Frequency Tracking
Intuition
To efficiently support both add and count operations, we use a hash map to track the frequency of each value in nums2. This allows us to quickly update counts when nums2 changes and to efficiently count valid pairs for any given sum.
Approach
- Store nums1 as-is (since it is small, up to 1000 elements).
- For nums2, maintain a frequency map (hash map) of value to count.
- For add(index, val):
- Decrement the count of the old value at nums2[index] in the frequency map.
- Update nums2[index] by adding val.
- Increment the count of the new value in the frequency map.
- For count(tot):
- For each value x in nums1, compute y = tot - x.
- Add the frequency of y in nums2 to the answer.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n1 + q * n1)
where n1 = len(nums1), q = number of count queries. Each count is O(n1), add is O(1). - 🧺 Space complexity:
O(n2)
for the frequency map of nums2 values.