AlgoMaster Logo

Find All Anagrams in a String

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Sliding Window with Two Hash Maps

Intuition:

The problem of finding all anagrams can be interpreted as finding all starting indices of substrings in s that are permutations of p. One direct way to approach this problem is by using a sliding window technique with the help of hash maps (or frequency arrays) to count character occurrences.

The idea is to maintain two frequency maps:

  • One for the characters in the string p.
  • Another for characters in the current window of s with the same length as p.

By sliding the window across s, we compare the frequency of characters in the current window to those in p. If they match, then the start index of this window is an anagram's starting point.

Code:

2. Sliding Window with Single Array

Intuition:

By utilizing a fixed-size frequency count array instead of hash maps, we can reduce the constant factors in our solution. Since we're dealing only with lowercase English letters, we can use arrays of size 26 to store frequencies.

The idea remains the same as above: maintain a sliding window of length p across the string s, but instead of using two hash maps, use two arrays to track the frequencies. This not only brings clarity but also slightly optimizes access and modification times since operations on arrays are generally faster than on hash maps.

Code: