Map Sum Pairs

Implement a MapSum class with insert, and sum methods.

For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.

For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.

Example 1: Input: insert("apple", 3), Output: Null Input: sum("ap"), Output: 3 Input: insert("app", 2), Output: Null Input: sum("ap"), Output: 5

Solution: Using Trie with delta value

The key point of this method is to use a delta value to update our trie node when same key is inserted with a different value.

  • If we insert the key for the first time, delta value is key's value.
  • If we are updating the key, then delta value is the difference between old key's value and new key's value.
class TrieNode {
public:
    int val;
    unordered_map<char, TrieNode*> children;

    TrieNode() : val(0) {};
    TrieNode(int val) : val(val) {};
};

class MapSum {
public:
    /** Initialize your data structure here. */
    MapSum() {
        root = new TrieNode();
    }

    void insert(string key, int val) {
        int delta = val - m[key];
        m[key] = val;

        TrieNode *cur = root;
        cur->val += delta;
        for (auto ch: key) {
            if (!cur->children.count(ch)) {
                cur->children[ch] = new TrieNode();
            }
            cur = cur->children[ch];
            cur->val += delta;            
        }
    }

    int sum(string prefix) {
        TrieNode *cur = root;
        for (auto ch: prefix) {
            if (!cur->children.count(ch)) return 0;
            cur = cur->children[ch];
        }
        return cur->val;
    }

private:
    unordered_map<string, int> m;
    TrieNode *root;
};

results matching ""

    No results matching ""