Tutorialspoint
Problem
Solution
Submissions

Find All Anagrams in a String

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

Write a C# program to find all the start indices of anagrams of a given pattern string in a text string. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.

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".
Constraints
  • 1 <= s.length, p.length <= 3 * 10^4
  • s and p consist of lowercase English letters
  • Time Complexity: O(n), where n is the length of string s
  • Space Complexity: O(1), as we're using fixed-size arrays
ArraysStringsIBMDropbox
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 the sliding window technique with frequency counting
  • Maintain a window of size p.Length and slide it through the string s
  • Use arrays or hash maps to store character frequencies
  • Compare character frequencies to determine if a window contains an anagram
  • Optimize by updating the frequencies as the window slides

Steps to solve by this approach:

 Step 1: Create two frequency arrays (or hash maps) for counting characters in p and the current window in s.
 Step 2: Initialize the frequency count for pattern p.
 Step 3: Initialize the first sliding window of size p.length() in s.
 Step 4: Check if the first window is an anagram of p.
 Step 5: Slide the window by adding a new character and removing the oldest character.
 Step 6: After each slide, check if the current window is an anagram of p.
 Step 7: If it is an anagram, add the starting index to the result.

Submitted Code :