Finding Pairs With a Certain Sum LeetCode solution in JavaScript

1
function Counter(arr) {
2
// input: array
3
// output: corresponding occurrence-based dictionary
4

5
let keyOccDict = {};
6

7
arr.forEach((val) => (keyOccDict[val] = (keyOccDict[val] || 0) + 1));
8

9
return keyOccDict;
10
}
11

12
var FindSumPairs = function (nums1, nums2) {
13
this.arrA = nums1;
14
this.arrB = nums2;
15

16
// maintain mapping between distinct number and occurrence for array A
17
this.dictA = Counter(this.arrA);
18

19
// maintain mapping between distinct number and occurrence for array B
20
this.dictB = Counter(this.arrB);
21

22
return;
23
};
24

25
FindSumPairs.prototype.add = function (index, val) {
26
// update mapping for arrB
27

28
let old_value = this.arrB[index];
29
this.arrB[index] += val;
30
let new_value = this.arrB[index];
31

32
this.dictB[old_value] = this.dictB[old_value] - 1;
33
this.dictB[new_value] = (this.dictB[new_value] || 0) + 1;
34

35
return;
36
};
37

38
FindSumPairs.prototype.count = function (tot) {
39
/*
40
Goal:
41

42
Find the method count of a + b = total,
43
where a comes from array A, and b comes from array B
44

45
apply the concept learned from Leetcode #1 Two sum
46
a + b = total <=> b = total - a
47

48
speed-up by dictionary
49
*/
50

51
let counter = 0;
52

53
for (const [a, occ_a] of Object.entries(this.dictA)) {
54
let b = tot - a;
55

56
counter += occ_a * (this.dictB[b] || 0);
57
}
58

59
return counter;
60
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0