Skip to content

Commit 0184408

Browse files
authored
Create 1865. Finding Pairs With a Certain Sum (#834)
2 parents 25aa408 + 2d0b0ec commit 0184408

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class FindSumPairs {
2+
private:
3+
vector<int> nums1; // Store nums1 as-is (never changes)
4+
vector<int> nums2; // Store nums2 for index-based updates
5+
unordered_map<int, int> freq; // Frequency map for nums2 values
6+
7+
public:
8+
FindSumPairs(vector<int>& nums1, vector<int>& nums2) {
9+
// Store both arrays
10+
this->nums1 = nums1;
11+
this->nums2 = nums2;
12+
13+
// Build frequency map for nums2
14+
// This helps us quickly find how many times each value appears
15+
for (int num : nums2) {
16+
freq[num]++;
17+
}
18+
}
19+
20+
void add(int index, int val) {
21+
// Get the old value at this index
22+
int oldVal = nums2[index];
23+
24+
// Decrease frequency of old value
25+
freq[oldVal]--;
26+
if (freq[oldVal] == 0) {
27+
freq.erase(oldVal); // Remove if frequency becomes 0
28+
}
29+
30+
// Update nums2 with new value
31+
nums2[index] += val;
32+
int newVal = nums2[index];
33+
34+
// Increase frequency of new value
35+
freq[newVal]++;
36+
}
37+
38+
int count(int tot) {
39+
int pairCount = 0;
40+
41+
// For each element in nums1, find its complement in nums2
42+
for (int num1 : nums1) {
43+
int complement = tot - num1; // What we need from nums2
44+
45+
// If complement exists in nums2, add its frequency to our count
46+
if (freq.find(complement) != freq.end()) {
47+
pairCount += freq[complement];
48+
}
49+
}
50+
51+
return pairCount;
52+
}
53+
};
54+
55+
/**
56+
* Your FindSumPairs object will be instantiated and called as such:
57+
* FindSumPairs* obj = new FindSumPairs(nums1, nums2);
58+
* obj->add(index,val);
59+
* int param_2 = obj->count(tot);
60+
*/

0 commit comments

Comments
 (0)