Finding Pairs With a Certain Sum - Problem
You are given two integer arrays nums1 and nums2. You need to implement a data structure that supports queries of two types:
Add: Add a positive integer to an element at a given index in the array nums2.
Count: Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (where 0 <= i < nums1.length and 0 <= j < nums2.length).
Implement the FindSumPairs class:
FindSumPairs(int[] nums1, int[] nums2)- Initializes the object with two integer arraysvoid add(int index, int val)- Addsvaltonums2[index]int count(int tot)- Returns the number of pairs(i, j)such thatnums1[i] + nums2[j] == tot
Input & Output
Example 1 — Basic Operations
$
Input:
nums1 = [1,1,2,2,2,3], nums2 = [1,4,5,2,5,4], operations = [["count",7],["add",1,2],["count",8],["count",4],["add",2,1],["count",5]]
›
Output:
[8,2,1,1]
💡 Note:
count(7): pairs (0,2),(0,4),(1,2),(1,4),(2,1),(2,3),(4,1),(4,3) = 8 pairs. add(1,2): nums2[1] = 4+2 = 6. count(8): pairs (2,1),(4,1) = 2 pairs. count(4): pair (2,0) = 1 pair.
Example 2 — Simple Case
$
Input:
nums1 = [1,2], nums2 = [3,4], operations = [["count",5],["add",0,1],["count",6]]
›
Output:
[2,2]
💡 Note:
count(5): pairs (0,1) and (1,0) where 1+4=5 and 2+3=5. add(0,1): nums2[0] = 3+1 = 4. count(6): pairs (0,1) and (1,0) where 1+5=6 and 2+4=6.
Example 3 — No Pairs Found
$
Input:
nums1 = [1,2], nums2 = [5,6], operations = [["count",3],["add",0,2],["count",5]]
›
Output:
[0,0]
💡 Note:
count(3): no pairs sum to 3. add(0,2): nums2[0] = 5+2 = 7. count(5): still no pairs sum to 5.
Constraints
- 1 ≤ nums1.length ≤ 1000
- 1 ≤ nums2.length ≤ 105
- 1 ≤ nums1[i] ≤ 109
- 1 ≤ nums2[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two arrays and sequence of operations
2
Process
Count pairs that sum to target, update nums2 values
3
Output
Results from count operations only
Key Takeaway
🎯 Key Insight: Use frequency maps to avoid recounting - store nums1 frequencies once, update nums2 frequencies dynamically
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code