Optimization challengeIntermediate
Sorting every window to find anagrams
Scenario
This function returns the start indices of every substring of s that is an anagram of p (lowercase letters, |s| = 3·10⁴, |p| up to 3·10⁴). It is correct but too slow when p is long. Optimize it to linear time.
Broken
1def find_anagrams(s, p):2 k = len(p)3 key = sorted(p)4 out = []5 for i in range(len(s) - k + 1):6 if sorted(s[i:i + k]) == key:7 out.append(i)8 return outThe corrected version appears here once you have revealed everything below.
Your task
- Give the current complexity in terms of
n = |s|andk = |p|, and plug in the worst-case sizes. - What does "anagram" actually require? Find a representation of a window that is cheaper than a sorted copy.
- Show how consecutive windows differ and how to update your representation in
O(1). - Write the
O(n)solution and describe how you check equality of the representation without anO(26)comparison per step (optional refinement).
OptimizationComplexity AnalysisImplementation
Work it out
Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.
Reveal
Progressive — each section builds on the previous one.
The bottleneck
Key observation
The fix
Edge cases
Complexity
What this tests
Self-check
Tick what your analysis covered. Be honest — this feeds your readiness profile.