Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/anagram/anagram.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import java.util.*;
public class GroupAnagramTogether {

public static List<List<String>> groupAnagrams(String[] strs) {

List<List<String>> result = new ArrayList<>();

//Initialize hashmap
HashMap<String, List<String>> map = new HashMap<>();

//Traverse a list of string
for(String str: strs){

//Convert to character array
char[] chArr = str.toCharArray();
//Sort character array
Arrays.sort(chArr);
//Create a string
String key = new String(chArr);

//Create a key from a sorted string
//if this key is found add new string element
if(map.containsKey(key)){
map.get(key).add(str);

} else {
List<String> strList = new ArrayList<>();
strList.add(str);
map.put(key, strList);
}
}

result.addAll(map.values());
return result;
}

public static void main(String[] args) {

String[] strs = {"abc", "bca", "elf", "aab", "fle", "cab", "lel", "123", "231", "324"};
List<List<String>> result = groupAnagrams(strs);
result.forEach(t -> System.out.println(t + " "));
}
}
4 changes: 3 additions & 1 deletion src/anagram/problem.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ Constraints:
```


*Expected Time Complexity: O(n)*
*Time Complexity: O(n * k) (k is the length of the largest string)*

*Space Complexity: O(n)*