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 | import java.util.*; |
⏱ 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.