Sparse Arrays

  • + 0 comments

    A O(strings+queries) solution in C++ using unordered_map where all operations used below are at O(1) according to to implementation document.

    vector<int> matchingStrings(vector<string> strings, vector<string> queries) {
        unordered_map<string, int> frequency;
        vector<int>results;
        
        //counts all occurances of str in strings and populates the frequency map
        for(string str: strings)
            frequency[str]++;
        //writes out the queries occurances in result
        for(string str: queries)
            results.push_back(frequency[str]);
        
         return results;
    }