DEV Community

Discussion on: Daily Challenge #204 - Partial Keys

Collapse
 
vidit1999 profile image
Vidit Sarkar • Edited

Hope I have got the problem right.
Here is the C++ solution

#include <bits/stdc++.h>
using namespace std;

class ObjectSpecial{
    map<string, int> mapSpecial;
    public:
    // constructor
    ObjectSpecial(map<string, int> mapObject){
        this->mapSpecial = mapObject;
    }

    // cpp map already stores the keys in alphabetical order
    // so start from first and if we find a key that starts with the partial key
    // then return its value
    // if key not found then return 0
    int operator[](string s){
        for(auto it : mapSpecial){

            // check if key starts with the given partial key s
            // if true then return corresponding value
            if(it.first.rfind(s,0) == 0)
                return it.second;
        }
        return 0;
    }
};

ObjectSpecial partialKeys(map<string, int> m){
    return ObjectSpecial(m);
}

// main function
int main(){
    ObjectSpecial o = partialKeys({{"abcd",1},{"abbd", 2}});
    cout << o["abcd"] << "\n"; // output : 1
    cout << o["ab"] << "\n"; // output : 2
    cout << o["k"] << "\n"; // output : 0 as key is not present
    cout << o["abc"] << "\n"; // output : 1
    cout << o["abd"] << "\n"; // output : 0 as key is not present
    return 0;
}