LeetCode: Finding Pairs With A Certain Sum Solution

1/**
2 * @param {number[]} nums1
3 * @param {number[]} nums2
4 */
5var FindSumPairs = function (nums1, nums2) {
6 this.nums1 = nums1
7 this.nums2 = nums2
8 this.occurences2 = nums2.reduce(
9 (acc, el) => acc.set(el, (acc.get(el) || 0) + 1),
10 new Map()
11 )
12}
13
14/**
15 * @param {number} index
16 * @param {number} val
17 * @return {void}
18 */
19FindSumPairs.prototype.add = function (index, val) {
20 const num = this.nums2[index]
21 const newNum = num + val
22 this.occurences2.set(num, this.occurences2.get(num) - 1)
23 this.occurences2.set(newNum, (this.occurences2.get(newNum) || 0) + 1)
24 this.nums2[index] = newNum
25}
26
27/**
28 * @param {number} tot
29 * @return {number}
30 */
31FindSumPairs.prototype.count = function (tot) {
32 let res = 0
33 for (const num1 of this.nums1) {
34 res += this.occurences2.get(tot - num1) || 0
35 }
36 return res
37}
38
39/**
40 * Your FindSumPairs object will be instantiated and called as such:
41 * var obj = new FindSumPairs(nums1, nums2)
42 * obj.add(index,val)
43 * var param_2 = obj.count(tot)
44 */

Comments

Loading comments...

Tags

leetcode

hash table

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Minimum Number Of Swaps To Make The Binary String Alternating

May 16, 2021

Previous Post

HoningJS

Search Posts