Question: https://leetcode.com/problems/group-anagrams/description/

So, I did solve an anagram problem a day before yesterday. I used the same method to check if it is an anagram or not.

The I simply iterated through the given list. Next I checked if the element is already added to some group or not. if it isn’t then I check if any element is an anagram of that element if is then add it to the group and checked set. Also, if there isn’t any anagram add it alone in the group.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if(len(s)==len(t)):
            s_l = list(s)
            t_l = list(t)
            s_l.sort()
            t_l.sort()
            if(s_l == t_l):
                return True
        return False

    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        checked = set()
        result = []
        for i in range(len(strs)):
            if strs[i] not in checked:
                temp = []
                temp.append(strs[i])
                checked.add(strs[i])
                for j in range(i+1, len(strs)):
                    if self.isAnagram(strs[j], strs[i]):
                        temp.append(strs[j])
                        checked.add(strs[j])
                result.append(temp)
        return result

I was in a hurry because of some work so I did not solve to optimize it today.