Find all Anagrams in a String Leetcode Solution

Find All Anagrams in a String Leetcode Problem :

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

jump game leetcode

Find All Anagrams in a String Leetcode Solution :

Constraints :

  • 1 <= s.length, p.length <= 3 * 104
  • s and p consist of lowercase English letters.

Example 1:

  • 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”.

Intuition :

  1. whenever all characters of p string matches with s string’s certain window
    save the leftmost position of the window.
  2. do this operation until the end of the string s

So clearly we need to count the frequency of

  1. p string
  2. s string’s current window (which is equal to length of p).

Approach :

  1. create two arrays s_coutp_count of size 26 and intialise it to zero.
  2. create an array to store the final answer ans
  3. corner case: a. if s size is empty or lesser than p
  4. count the frequecies of s, p until the size of p (this is nothing but our first sliding window.)
  5. if s_count matches with the p_count store the leftmost index of the array, here in this case is starting positon.
  6. we already travesed 0 to p.size()-1, so we are travesing p.size() to s.size() of string s
  7. count the next character of s
  8. and remove the leftmost character of the sliding window from count array of s. (nothing but we are maintaining the current sliding window.)
  9. check whether current sliding count matches with p_count, if yes store the result.
  10. return ans.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription