Skip to content

Latest commit

 

History

History

677

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Implement the MapSum class:

  • MapSum() Initializes the MapSum object.
  • void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
  • int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.

 

Example 1:

Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]

Explanation
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);  
mapSum.sum("ap");           // return 3 (apple = 3)
mapSum.insert("app", 2);    
mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)

 

Constraints:

  • 1 <= key.length, prefix.length <= 50
  • key and prefix consist of only lowercase English letters.
  • 1 <= val <= 1000
  • At most 50 calls will be made to insert and sum.

Companies:
Akuna Capital

Related Topics:
Hash Table, String, Design, Trie

Solution 1. Map

// OJ: https://leetcode.com/problems/map-sum-pairs/
// Author: github.com/lzl124631x
// Time:
//      MapSum: O(1)
//      insert: O(WlogN) where W is word length
//      sum: O(NW)
// Space: O(NW)
class MapSum {
private:
    map<string, int> m;
public:
    MapSum() {}
    
    void insert(string key, int val) {
        m[key] = val;
    }
    
    int sum(string prefix) {
        int sum = 0;
        for (auto start = m.lower_bound(prefix); start != m.end(); ++start) {
            if (start->first.compare(0, prefix.size(), prefix) != 0) break;
            sum += start->second;
        }
        return sum;
    }
};

Solution 2. Trie + Unordered Map

// OJ: https://leetcode.com/problems/map-sum-pairs/
// Author: github.com/lzl124631x
// Time:
//      MapSum: O(1)
//      insert: O(W) where W is word length
//      sum: O(W)
// Space: O(NW)
struct TrieNode {
    TrieNode *next[26] = {};
    int sum = 0;
};
class MapSum {
    TrieNode root;
    unordered_map<string, int> m;
public:
    MapSum() {}
    
    void insert(string key, int val) {
        int diff = val;
        if (m.count(key)) diff = val - m[key];
        m[key] = val;
        auto node = &root;
        for (char c : key) {
            if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
            node = node->next[c - 'a'];
            node->sum += diff;
        }
    }
    
    int sum(string prefix) {
        auto node = &root;
        for (char c : prefix) {
            node = node->next[c - 'a'];
            if (!node) return 0;
        }
        return node->sum;
    }
};