If you've seen a duplicate to this question, please feel free to link it because I haven't seen this question before.
For an interview question, I had the following:
1) Generate all anagrams of a string
Ex. anagrams("dog") -> ["dog","dgo","odg","ogd","gdo","god"]
2) Generate all k-size anagrams of a string
Ex. anagrams("dog",k = 2) -> ["do","od","dg","gd","go","og"]
I came up with a solution to (1) by recursing on an input string minus its first char, and inserting the first char into every position of every returned anagram:
def anagrams(word):
if len(word) == 1:
return [word]
current = word[0]
anags = []
for anag in anagrams(word[1:]):
anags += [anag[:i] + current + anag[i:] for i in range(len(anag) + 1)]
return anags
Can anyone come up with Java or Python solution for (2) with the signature def anagrams(word, k = None)
or in Java List<String> anagrams(String word, int k)
?