Skip to main content

1865.js

/** ------------------------------------------------------------------------------
*
* 1865. Finding Pairs With a Certain Sum
* Topics: Array, Hash Table
* https://leetcode.com/problems/finding-pairs-with-a-certain-sum/description/?envType=daily-question&envId=2025-07-06
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums1
* @param {number[]} nums2
*/
var FindSumPairs = function (nums1, nums2) {
this.nums1 = nums1
this.nums2 = nums2
this.map2 = new Map()

for (const num of nums2) {
this.map2.set(num, (this.map2.get(num) || 0) + 1)
}
}

/**
* @param {number} index
* @param {number} val
* @return {void}
*/
FindSumPairs.prototype.add = function (index, val) {
const oldVal = this.nums2[index]
this.map2.set(oldVal, this.map2.get(oldVal) - 1)

this.nums2[index] += val
const newVal = this.nums2[index]
this.map2.set(newVal, (this.map2.get(newVal) || 0) + 1)
}

/**
* @param {number} tot
* @return {number}
*/
FindSumPairs.prototype.count = function (tot) {
let count = 0

for (let num1 of this.nums1) {
let num2 = tot - num1
if (this.map2.has(num2)) count += this.map2.get(num2)
}

return count
}

console.log(
new FindSumPairs(
["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"],
[
[1, 1, 2, 2, 2, 3],
[1, 4, 5, 2, 5, 4],
],
),
)