πŸ”Ή 14. Longest Common Prefix

πŸ”— https://leetcode.com/problems/longest-common-prefix/

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string prefix = "";
        for(int i = 0; i < strs[0].size(); i++) {
            string first = strs[0];
            for (auto s: strs) {
                if (i >= s.size() || first[i] != s[i]) {
                    return prefix;
                }
            }
            prefix += first[i];
        }
        return prefix;
    }
};

πŸ”Ή 49. Group Anagrams

πŸ”— https://leetcode.com/problems/group-anagrams/

πŸš€ Approach 1: Sorting

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> um;
 
        for(auto &i : strs){
            string sorted_str = i;
            sort(sorted_str.begin(), sorted_str.end());
            um[sorted_str].push_back(i);
        }
 
        vector<vector<string>> ans;
        for(auto &i: um){
            ans.push_back(i.second);
        }
 
        return ans;
    }
};

πŸš€ Approach 2: Frequency Count (Optimal)

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<vector<int>, vector<string>> um;
 
        for(auto &i: strs) {
            vector<int> freq(26);
            for(auto &c: i)
                freq[c - 'a']++;
 
            um[freq].push_back(i);
        }
 
        vector<vector<string>> ans;
        for(auto &i: um)
            ans.push_back(i.second);
 
        return ans;
    }
};

⚠️ Notes

  • unordered_map faster but can’t hash vector easily
  • map works but slightly slower