given an array of strings, return a 2d array that each element in that is a grouped array contains anagrams.

first, we need to iterate this array at least once.
and then, we need to group them based on the exactly same characters they used. but how can we know if two strings has the same letters? we can divide string into characters and sort them, and compare them. but it’s very time consuming. or we can use hashmap, so we only needs to iterate the whole given array one time.

then what should we use as the key? so that we can quickly find what the current string belongs to?
all I can think of is: use a1 b1 c2 as a key, and covert strings into something like this. if we have a key like that in hashmap, add it in corresponding value. if it is not, then we put in a new one.

and eventually, i decided to use format as “abcc” as the key.
so the time complexity will be (length of input array) * (longest str log longest str)

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        if (strs == null || strs.length == 0) return res;
        
        HashMap<String, List<String>> map = new HashMap();
        
        for (String str: strs) {
            
            String key = convert(str);
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<>());
            }
            map.get(key).add(str);
        }
        return new ArrayList<>(map.values());
        
    }
    
    private String convert(String str) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        
        StringBuilder sb = new StringBuilder();
        for (char c: chars) {
            sb.append(c);
        }
        //System.out.println(sb.toString());
        return sb.toString();
    }
    
    
}

after this, I checked the answer, it’s something like my idea.