Find group of strings that are anagrams
<p>This question refers to <a href="http://www.lintcode.com/en/problem/anagrams/" rel="nofollow">this problem on lintcode</a>. 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.</p>

<pre><code>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
</code></pre>

<p><strong>Update:</strong> Just to add, not looking for built-in pythonic solutions such as using <code>Counter</code> which are already optimized. Have added Mike's suggestions, but still exceeding time-limit.</p>

<p>Instead of comparing all pairs of strings, you can just create a dictionary (or <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>) mapping each of the letter-counts to the words having those counts. For getting the letter-counts, you can use <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>. Afterwards, you just have to get the values from that dict. If you want all words that are anagrams of any other words, just merge the lists that have more than one entry.</p>

<pre><code>strings = ["cat", "act", "rat", "hut", "tar", "tact"]
anagrams = defaultdict(list)

for s in strings:
    anagrams[frozenset(Counter(s).items())].append(s)

print([v for v in anagrams.values()])
# [['hut'], ['rat', 'tar'], ['cat', 'act'], ['tact']]
print([x for v in anagrams.values() if len(v) &gt; 1 for x in v])
# ['cat', 'act', 'rat', 'tar']
</code></pre>

<p>Of course, if you prefer not to use builtin functionality you can with just a few more lines just as well use a regular <code>dict</code> instead of <code>defaultdict</code> and write your own <code>Counter</code>, similar to what you have in your <code>isanagram</code> method, just without the comparison part.</p>

python string anagram