0

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!

1 Answer 1

0

Your function returns tuple

(anagrams, self.groupAnagrams(strs))

So, when it is applied recursively, each call inserts another tuple into the previous one. And this creates nested brackets. Try replacing your return statement with

return [anagrams]+self.groupAnagrams(strs)

This should make your function return list which will grow with each recursive call without adding excessive brackets.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.