Algorithm-Day09-Find-All-Angarams-in-a-String-lc-438

🧩 Problem Description

Given two strings s and p, return all the start indices of p‘s anagrams in s.

You may return the answer in any order.

Example:

Input: s = “cbaebabacd”, p = “abc”
Output: [0, 6]

Explanation:

  • The substring starting at index 0 is “cba”, an anagram of “abc”.
  • The substring starting at index 6 is “bac”, another anagram.

💡 Brute Force (Not Efficient)

Generate every substring of s with length p.length() and check if it is an anagram.

  • Time: O(n * k log k) if sorting is used
  • ❌ Too slow for large inputs

💡 Optimized Approach: Sliding Window + Frequency Count

  • Use two arrays of size 26 (for lowercase letters)
  • One array stores frequency of characters in p
  • The second tracks the sliding window in s
  • Compare the arrays at each step (or use a match count to speed up)

🔢 Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.*;

class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();

if (s.length() < p.length()) return result;

int[] pCount = new int[26];
int[] sCount = new int[26];

for (char c : p.toCharArray()) {
pCount[c - 'a']++;
}

for (int i = 0; i < s.length(); i++) {
// Add new character to current window
sCount[s.charAt(i) - 'a']++;

// Remove character that's left the window
if (i >= p.length()) {
sCount[s.charAt(i - p.length()) - 'a']--;
}

// Compare frequency arrays
if (Arrays.equals(pCount, sCount)) {
result.add(i - p.length() + 1);
}
}

return result;
}
}

⏱ Time and Space Complexity

  • Time Complexity: O(n)
    Each character processed once, comparison takes O(26) = constant
  • Space Complexity: O(1)
    Only fixed-size arrays used (no hashmap needed)

✍️ Summary

  • This is a classic fixed-length sliding window problem
  • Using character count arrays instead of sorting or hashing improves performance significantly
  • Similar patterns appear in Minimum Window Substring, Permutation in String, etc.

Mastering this technique is key to solving many real-time window comparison problems efficiently.