package GroupAnagrams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * https://leetcode.com/problems/group-anagrams/
 * <p>
 * Given an array of strings, group anagrams together.
 *
 * <p>
 * Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
 * Output:
 * [
 * ["ate","eat","tea"],
 * ["nat","tan"],
 * ["bat"]
 * ]
 * <p>
 * Note:
 * <p>
 * All inputs will be in lowercase.
 * The order of your output does not matter.
 */
public class GroupAnagramsSolution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        if (strs != null) {
            for (String string : strs) {
                char[] charArray = string.toCharArray();
                Arrays.sort(charArray);
                String sortedString = new String(charArray);

                if (!map.containsKey(sortedString)) {
                    map.put(sortedString, new ArrayList<>());
                }

                map.get(sortedString).add(string);
            }
        }
        return new ArrayList<>(map.values());
    }
}
