Output Limit Exceeded, Any thoughts why?


  • 0
    S
        class Solution {
    private:
        // Given a string calculates the hashcode using a simple formula: hash code = 'charNumber' * 'charCount'
        // Say the string is "abcab" then the code = 0*1 + 1*1 + 2*1 + 0*2 + 1*2
        int calculateHashCode(string &s)
        {
            int code = 0;
            map<char, int> charCount;
            for(int i=0; i < s.length(); ++i)
            {
                auto it = charCount.find(s[i]);
                if(it != charCount.end())
                {
                    ++it->second;
                }
                else
                {
                    charCount[s[i]] = 1;
                }
            }
            
            for(auto it = charCount.begin(); it != charCount.end(); ++it)
            {
                code += (it->first-'a')*(it->second);
            }
            return code;
        }
    public:
        vector<string> anagrams(vector<string> &strs) {
            vector<string> res;
            map<int, vector<int> > groupMap; // stores a map from hashcode to strs index having the same hashcode
            
            // Calculate hashcode for all the input strings and populate the groupMap
            for(int i=0; i < strs.size(); ++i)
            {
                int code = calculateHashCode(strs[i]);
                auto it = groupMap.find(code);
                if(it != groupMap.end())
                {
                    it->second.push_back(i);
                }
                else
                {
                    vector<int> temp;
                    temp.push_back(i);
                    groupMap[code] = temp;
                }
            }
            
            // All string in groupMap that have a group greater than size 1 are push onto the result vector
            for(auto it = groupMap.begin(); it != groupMap.end(); ++it)
            {
                if(it->second.size() > 1)
                {
                    for(int i=0; i<it->second.size(); ++i)
                    {
                        res.push_back(strs[it->second[i]]);
                    }
                }
            }
            return res;
            
        }
    };
    

    I think its a good idea to show the executed test case for which the OLE happened.


Log in to reply
 

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