iLabs Interview Question
Senior Software Development EngineersCountry: India
Interview Type: Phone Interview
For each word in the dictionary that has the same length as the input string, sort the characters in the word and see if it's the same as the input string when sorted.
static LinkedList<String> findAnagrams(String s, HashSet<String> dict) {
s = sort(s);
LinkedList<String> anagrams = new LinkedList<String>();
for(String word : dict) {
if(word.length() == s.length() && sort(word).equals(s)) {
anagrams.add(word);
}
}
return anagrams;
}
static String sort(String s) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
Generate all the anagrams of the word and then look up into the dictionary for each anagram.
For the matches found in the dictionary return the list.
@subahjit
I suppose, you meant to generate all the permutations of the given input word, but not the "anagrams".
1. Sort the characters in each word in the dictionary and use that as key to add in HashMap with value as linked list in which we need to add words as they are.
- arunbabuasp July 07, 20132. Sort the characters in 'given word' and using that as key retrieve the linked list from above HashMap.
3. Print the contents of above linked list.