I've been trying to find a solution to this problem however I can not seem to find out how to match my output with the expected output.
Here's the problem:
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
And here's my solution:
class Solution(object):
def groupAnagrams(self, strs):
if len(strs) == 0:
return []
else:
first_word = strs[0]
anagrams = [first_word]
strs = strs[1:]
for word in strs:
x = True
for letter in word:
if word.count(letter) != first_word.count(letter):
x = False
break
if x:
anagrams.append(word)
for idx in anagrams:
if idx in strs:
strs.remove(idx)
return anagrams, self.groupAnagrams(strs)
Here's what my output is:
[["eat","tea","ate"],[["tan","nat"],[["bat"],[]]]]
And here's what my expected output is:
[["bat"],["nat","tan"],["ate","eat","tea"]]
I am still trying to get comfortable with recursion, so it's hard for me to visualize what is happening (even with a debugger). Any help on what is causing additional brackets to form is appreciated, thanks!