Tutorialspoint
Problem
Solution
Submissions

All Anagrams in a String

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to find all the start indices of anagrams of string p in string s. An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once. Use the sliding window technique with character frequency counting.

Example 1
  • Input: s = "abab", p = "ab"
  • Output: [0, 2]
  • Explanation:
    • We need to find anagrams of "ab" in "abab".
    • At index 0: substring "ab" is an anagram of "ab".
    • At index 1: substring "ba" is an anagram of "ab".
    • At index 2: substring "ab" is an anagram of "ab".
    • Therefore, anagrams start at indices [0, 2].
Example 2
  • Input: s = "abcab", p = "abc"
  • Output: [0]
  • Explanation:
    • We need to find anagrams of "abc" in "abcab".
    • At index 0: substring "abc" is an anagram of "abc".
    • At index 1: substring "bca" is an anagram of "abc".
    • At index 2: substring "cab" is an anagram of "abc".
    • Therefore, anagrams start at indices [0].
Constraints
  • 1 <= s.length, p.length <= 3 * 10^4
  • s and p consist of lowercase English letters only
  • Time Complexity: O(n) where n is the length of string s
  • Space Complexity: O(1) since we only store at most 26 characters
StringsMapCognizantAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use sliding window technique with a window size equal to the length of string p
  • Create frequency maps for characters in string p and the current window
  • Slide the window one character at a time across string s
  • When adding a new character, increment its count; when removing, decrement its count
  • Compare frequency maps at each step to check if current window is an anagram
  • Use a helper function to compare two frequency maps efficiently

Steps to solve by this approach:

 Step 1: Create frequency maps for the pattern string p and initialize an empty result array.

 Step 2: Create a sliding window of size equal to p.length and initialize its frequency map.
 Step 3: Check if the initial window forms an anagram with p by comparing frequency maps.
 Step 4: Slide the window one position to the right, adding the new character and removing the old character.
 Step 5: Update the window's frequency map by incrementing count for new character and decrementing for old character.
 Step 6: Compare the updated window frequency map with pattern frequency map to check for anagram.
 Step 7: If frequencies match, add the current window's start index to the result array and continue sliding.

Submitted Code :