sagelearnai

Map Sum Pairs

Difficulty: Medium · Pattern: Tries · LeetCode #677

Design MapSum:

  • insert(key, val): set key → val. If the key already exists, overwrite its value.
  • sum(prefix): return the sum of the values of all keys that start with prefix.

Example

text
insert("apple", 3); sum("ap") → 3
insert("app", 2);   sum("ap") → 5
insert("apple", 1); sum("ap") → 3     (apple overwritten 3 → 1)

Hints

  1. Make every trie node store the total of all keys passing through it. Then sum(prefix) is a single walk.
  2. To handle overwrites, add the delta val − oldVal along the path, not val.

Approach

Keep a dict vals of the current value per key, plus a trie where each node has a score.

  • insert(key, val): delta = val − vals.get(key, 0), store vals[key] = val, then walk/create the path for key (including the root) adding delta to each node's score.
  • sum(prefix): walk the prefix. Return 0 if it falls off the trie, otherwise the score of the last node.

Both operations take O(len) time. The naive version scans every key on each sum, costing O(#keys × len).

Complexity

Time: O(len) per call. Space: O(total key characters).

Python solution
class MapSum:
    def __init__(self):
        self.vals = {}
        self.root = {'#': 0}

    def insert(self, key, val):
        delta = val - self.vals.get(key, 0)
        self.vals[key] = val
        node = self.root
        node['#'] += delta
        for ch in key:
            node = node.setdefault(ch, {'#': 0})
            node['#'] += delta

    def sum(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node:
                return 0
            node = node[ch]
        return node['#']
JavaScript solution
class MapSum {
  constructor() { this.vals = new Map(); this.root = { score: 0, kids: {} }; }
  insert(key, val) {
    const delta = val - (this.vals.get(key) || 0);
    this.vals.set(key, val);
    let node = this.root;
    node.score += delta;
    for (const ch of key) {
      node = node.kids[ch] ??= { score: 0, kids: {} };
      node.score += delta;
    }
  }
  sum(prefix) {
    let node = this.root;
    for (const ch of prefix) { node = node.kids[ch]; if (!node) return 0; }
    return node.score;
  }
}