DEV Community

Debesh P.
Debesh P.

Posted on

49. Group Anagrams | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/group-anagrams/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/group-anagrams/solutions/7497698/most-optimal-solution-beats-500-hashmap-nwzcb


leetcode 49


Solution

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {

        if (strs == null || strs.length == 0) {
            return new ArrayList<>();
        }

        Map<String, List<String>> freqStringMap = new HashMap<>();

        for (String str : strs) {
            String freqKey = getFreqKey(str);
            if (freqStringMap.containsKey(freqKey)) {
                freqStringMap.get(freqKey).add(str);
            } else {
                List<String> strList = new ArrayList<>();
                strList.add(str);
                freqStringMap.put(freqKey, strList);
            }
        }

        return new ArrayList<>(freqStringMap.values());
    }

    private String getFreqKey(String str) {
        int[] arr = new int[26];
        for (char c : str.toCharArray()) {
            arr[c - 'a']++;
        }

        StringBuilder sb = new StringBuilder();
        char c = 'a';
        for (int i : arr) {
            sb.append(c);
            sb.append(i);
            c++;
        }

        return sb.toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)