Find group of strings that are anagrams This question refers to this problem on lintcode. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it  be improved? Maybe I can decrease the number of comparisons I make in the outer loop.

class Solution:
    # @param strs: A list of strings
    # @return: A list of strings
    def anagrams(self, strs):
        # write your code here
        ret=set()
        for i in range(0,len(strs)):
            for j in range(i+1,len(strs)):
                if i in ret and j in ret:
                    continue
                if Solution.isanagram(strs[i],strs[j]):
                    ret.add(i)
                    ret.add(j)

        return [strs[i] for i in list(ret)]


    @staticmethod
    def isanagram(s, t):
        if len(s)!=len(t):
            return False
        chars={}
        for i in s:
            if i in chars:
                chars[i]+=1
            else:
                chars[i]=1

        for i in t:
            if i not in chars:
                return False
            else:
                chars[i]-=1
                if chars[i]&lt;0:
                    return False

        for i in chars:
            if chars[i]!=0:
                return False
        return True
Different algorithm

Instead of considering all pairs of strings which leads to a O(n^2) behavior (where n is the number of strings), you could operate differently and use a dictionnary to group words based on some kind of signature with would be the same for anagrams and different for non-anagrams.

In your case, you could use the "sorted" version of a word as a signature : only 2 anagrams will be indentical once sorted. Once you've determined how to compute this, you can easily define a dictionnary mapping sorted words to the anagrams they correspond to.

This is a typical situation where the setdefault method is useful.

You can write something like:

t1 = ["lint", "intl", "inlt", "code"] # return ["lint", "inlt", "intl"].
t2 = ["ab", "ba", "cd", "dc", "e"] # return ["ab", "ba", "cd", "dc"].

def anagrams(word_list):
    anagrams = {}
    for w in word_list:
        anagrams.setdefault(''.join(sorted(w)), []).append(w)
    # print(anagrams)
    return sorted(  # sort is to make results always the same
                [w for anagrams in anagrams.values()
                    if len(anagrams) &gt; 1
                        for w in anagrams])

assert anagrams(t1) == ['inlt', 'intl', 'lint']
assert anagrams(t2) == ['ab', 'ba', 'cd', 'dc']