Skip to content

How to Fix Find All Anagrams in String Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Find All Anagrams in String Errors. We cover key concepts, practical examples, and best practices.

Fix find all anagrams in string errors when character count comparison not reset or window not properly tracked.

Quick Fix

Wrong

def ana(s,p):
    ns,np=len(s),len(p)
    if ns<np: return []
    sc=Counter(s[:np]); pc=Counter(p)
    res=[0] if sc==pc else []
    for i in range(np,ns):
        sc[s[i]]+=1
        sc[s[i-np]]-=1
        if sc[s[i-np]]==0: del sc[s[i-np]]
        if sc==pc: res.append(i-np+1)
    return res

Deleting zero-count keys is optional but good practice. Works without it.

from collections import Counter
def ana(s,p):
    ns,np=len(s),len(p)
    if ns<np: return []
    sc=Counter(s[:np]); pc=Counter(p)
    res=[0] if sc==pc else []
    for i in range(np,ns):
        sc[s[i]]+=1; sc[s[i-np]]-=1
        if sc[s[i-np]]==0: del sc[s[i-np]]
        if sc==pc: res.append(i-np+1)
    return res
s='cbaebabacd', p='abc' -> [0,6] (substrings 'cba','bac'). O(n).

Prevention

Sliding window counter. Add new char, remove old char, compare counters.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is anagram search?

Find all start indices where substring is anagram of target. O(n).

Counter comparison?

sc==pc compares both Counter objects. O(26) for lowercase letters.

Delete zero keys?

Prevents Counter from having keys with value 0. Not required but cleaner.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro