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
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 :-
- Create the HashMap object of type String as a Key and List of Strings as a value.
- Traverse the input list of strings from start to end and for each String S, convert it into a character array.
- Sort the character array created in the last step and convert it into a string.
- Put the sorted string as a key and List of Strings (after adding String S) as a value into the HashMap.
- 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
- First Unique Character in a String
- Check If Word Is Valid After Substitutions
- 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.
1 thought on “Group Anagrams | String Problem | LeetCode 49”
[…] + View Here […]