LeetcodeAug 23, 2025

Find All Anagrams in a String

Hazrat Ali

Leetcode

Given two strings s and p, return an array of all the start indices of p's  in s. You may return the answer in any order.

 

Example 1:

Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

Solution
/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
const findAnagrams = (s, p) => {
 
  const map = {};
  for (let c of p) {
    map[c] = ~~map[c] + 1;
  }

  let counter = p.length;
  let result = [];

 
  for (let i = 0, j = 0; j < s.length; j++) {
   
    if (map[s[j]]-- > 0) {
      counter--;
    }

   
    while (counter === 0) {
      if (j - i + 1 === p.length) {
        result.push(i);
      }

      if (map[s[i++]]++ === 0) {
        counter++;
      }
    }
  }

  return result;
};




Comments