#438

Find All Anagrams in a String

Medium
Hash TableStringSliding WindowHash MapSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a sliding window approach with a frequency count of characters. This way, we can efficiently check if the current window is an anagram of 'p' without sorting each time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency count for characters in 'p'.
  2. 2Step 2: Initialize a sliding window of size equal to 'p' and maintain a frequency count for the current window in 's'.
  3. 3Step 3: Slide the window across 's', updating the frequency count by adding the new character and removing the old character.
  4. 4Step 4: After each slide, compare the frequency counts. If they match, record the starting index.
solution.py16 lines
1from collections import Counter
2
3def findAnagrams(s, p):
4    p_count = Counter(p)
5    s_count = Counter(s[:len(p)])
6    result = []
7    if s_count == p_count:
8        result.append(0)
9    for i in range(len(p), len(s)):
10        s_count[s[i]] += 1
11        s_count[s[i - len(p)]] -= 1
12        if s_count[s[i - len(p)]] == 0:
13            del s_count[s[i - len(p)]]
14        if s_count == p_count:
15            result.append(i - len(p) + 1)
16    return result

Complexity note: The time complexity is O(n) since we traverse the string 's' once while maintaining a frequency count. The space complexity is O(n) due to the storage of character counts for 'p' and the current window.

  • 1Anagrams have the same character frequency.
  • 2Using a sliding window allows efficient checking without repeated sorting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.