Group Anagrams | String Problem | LeetCode 49

4 years ago Lalit Bhagtani 1

Problem Statement

You have given an array of strings, write a program to group all the anagrams.

Note :- Strings consists of only lowercase English letters.

Example 

Group Anagrams

Input :- ["eat", "tea", "tan", "ate", "nat", "bat"]
Output :-
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Input :- ["abcd", "bcad", "eaft", "tfea", "abc", "def"],
Output :-
[
  ["abc"],
  ["def"],
  ["abcd", "bcad"],
  ["eaft", "tfea"]
]

Solution

This problem can be solved in following steps :-

  1. Create the HashMap object of type String as a Key and List of Strings as a value.
  2. Traverse the input list of strings from start to end and for each String S, convert it into a character array.
  3. Sort the character array created in the last step and convert it into a string.
  4. Put the sorted string as a key and List of Strings (after adding String S) as a value into the HashMap.
  5. Return the list of values of HashMap as a result.

Program

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

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String[] anagrams = new String[] {"abcd", "bcad", "eaft", "tfea", "abc", "def"};
		List<List<String>> result = main.groupAnagrams(anagrams);
		for(List<String> list : result) {
			for(String str : list) {
				System.out.print(str + ", ");
			}
			System.out.println();
		}
	}
	
	/* Solution */
	public List<List<String>> groupAnagrams(String[] strs) {
        
        String temp;
        char[] array;
        List<String> list;
        Map<String, List<String>> map = new HashMap<>();
        for(String str: strs){
            
            array = str.toCharArray();
            Arrays.sort(array);
            temp = String.valueOf(array);
            
            if(map.containsKey(temp)){
                map.get(temp).add(str);
            }else {
                list = new ArrayList<>();
                list.add(str);
                map.put(temp, list);
            }
            
        }
        
        List<List<String>> result = new ArrayList<>();
        for(List<String> value: map.values()){
            result.add(value);
        }
        return result;        
    }
}

Result

abc, 
def, 
abcd, bcad, 
eaft, tfea, 

Similar Post

  1. First Unique Character in a String
  2. Check If Word Is Valid After Substitutions
  3. Convert Roman Number to Decimal

That’s all for Group Anagrams in Java, If you liked it, please share your thoughts in a comments section and share it with others too.