Posts Group Anagrams
Post
Cancel

Group Anagrams

This question is part of NeetCode150 series.

Problem Description

Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
leetcode

Solution

The idea is that the sorted version of two strings which are Anagrams of each other will be same. So, we key this sorted form as the Key of a HashMap and keep insert the strings in the list of string (value for that key).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
    
    public List<List<String>> groupAnagrams(String[] strs) {
        
        Map<String, List> map = new HashMap<>();
        
        for(int i=0; i<strs.length; i++){
            
            String s = strs[i];
            String sorted_s = sortString(s);
            
            if(map.containsKey(sorted_s)){
                map.get(sorted_s).add(s);
            }else{
                List<String> tempList = new ArrayList<>();
                tempList.add(s);
                map.put(sorted_s, tempList);
            }
            
        }
        
        return new ArrayList(map.values());
        
    }
    
    public String sortString(String s){
        char[] ca = s.toCharArray();
        Arrays.sort(ca);
        return String.valueOf(ca);
    }
    
}
This post is licensed under CC BY 4.0 by the author.