Simple C++ Solution with comments

  • 0

    class MapSum {
    map<string,int> m;
    /** Initialize your data structure here. */
    MapSum() {

    void insert(string key, int val) {
        //add key and val to map
        m[key] = val;
    int sum(string prefix) {
        int sum = 0;
        map<string,int>::iterator it;
        // Iterate through map and check if prefix equals to any of the keys in the map
        for(it = m.begin();it != m.end();it++){
            //Get the string size equal to the prefix size
            string str(it->first.begin(),it->first.begin()+prefix.size());
            if(prefix == str)
                sum += it->second;
        return sum;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.