Tutorialspoint
Problem
Solution
Submissions

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 pattern string p in a text string s. 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. Return the result as an array of starting indices.

Example 1
  • Input: s = "abab", p = "ab"
  • Output: [0, 2]
  • Explanation:
    • The substring starting at index 0 is "ab", which is an anagram of "ab".
    • The substring starting at index 2 is "ab", which is an anagram of "ab".
    • Both substrings have the same character frequency as pattern "ab".
    • Therefore, return indices [0, 2].
Example 2
  • Input: s = "abcdefg", p = "abc"
  • Output: [0]
  • Explanation:
    • The substring starting at index 0 is "abc", which is an anagram of "abc".
    • No other substring of length 3 forms an anagram of "abc".
    • Checking all positions: "bcd", "cde", "def", "efg" - none match.
    • Therefore, return [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 length of string s
  • Space Complexity: O(1) as we use fixed size arrays for character counts
  • Use sliding window technique for optimal solution
StringsHCL TechnologiesSamsung
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 two frequency arrays to track character counts
  • Create frequency arrays for pattern p and current window in string s
  • Initialize the first window of size equal to pattern length
  • Compare frequency arrays to check if current window is an anagram
  • Slide the window by removing leftmost character and adding new rightmost character
  • Continue until the window reaches the end of string s

Steps to solve by this approach:

 Step 1: Check if the string s is shorter than pattern p; if so, return empty result.
 Step 2: Create frequency arrays to count characters in pattern p and current sliding window.
 Step 3: Initialize the pattern frequency array by counting all characters in p.
 Step 4: Initialize the first window of size equal to pattern length and count its character frequencies.
 Step 5: Compare the two frequency arrays; if equal, add starting index 0 to results.
 Step 6: Slide the window by adding the new character and removing the character that goes out of window.
 Step 7: After each slide, compare frequency arrays and add valid starting indices to results.

Submitted Code :