Find All Anagrams in a String

Write a code to find all Anagrams in a String. Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.

Both the strings only consist of lowercase English letters. The length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

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

What is Anagram?

Two strings are said to be anagrams of each other, if it contains the same character only the order of characters in both strings is different. 

For example – The strings car and rac are anagrams of each other.

This problem is the toughest version of check whether two strings are anagrams of each other.

Find All Anagrams in a String

Find All Anagrams in a String – Java Code

In this example, I’ll discuss the approach using a map and a sliding window. The sliding window size will be equal to the length of the string p. Instead of using HashMap here, we are going to use an array of fixed sizes (26).

As in the problem statement, it is already mentioned that both the string consists of lowercase English letters.

The time complexity of this approach is O(n). Its space complexity is O(1), as we are using a fixed-size array that doesn’t depend on the input length.

Find All Anagrams in a String Video Tutorial

Group Anagrams together

Data Structure Video Tutorials

Programming Questions on Arrays

Programming Questions on Binary Tree

Programming Questions on Linked List

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.