-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0677-map-sum-pairs.js
More file actions
53 lines (44 loc) · 1.24 KB
/
0677-map-sum-pairs.js
File metadata and controls
53 lines (44 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Map Sum Pairs
* Time Complexity: O(L)
* Space Complexity: O(N*L)
*/
var TrieNode = function () {
this.children = new Map();
this.pathSum = 0;
};
var MapSum = function () {
this.trieRoot = new TrieNode();
this.keyToValueMap = new Map();
};
MapSum.prototype.insert = function (key, val) {
let previousValue = this.keyToValueMap.get(key) || 0;
let valueDifference = val - previousValue;
this.keyToValueMap.set(key, val);
let currentNode = this.trieRoot;
let keyLength = key.length;
for (
let currentPosition = 0;
currentPosition < keyLength;
currentPosition++
) {
let charCurrent = key[currentPosition];
if (!currentNode.children.has(charCurrent)) {
currentNode.children.set(charCurrent, new TrieNode());
}
currentNode = currentNode.children.get(charCurrent);
currentNode.pathSum += valueDifference;
}
};
MapSum.prototype.sum = function (prefix) {
let seekNode = this.trieRoot;
let prefixLength = prefix.length;
for (let charIndex = 0; charIndex < prefixLength; charIndex++) {
let currentCharacter = prefix[charIndex];
if (!seekNode.children.has(currentCharacter)) {
return 0;
}
seekNode = seekNode.children.get(currentCharacter);
}
return seekNode.pathSum;
};