Find All Anagrams in a String

Given a string STR and a non-empty string PTR, your task is to identify all starting indices of PTR’s anagrams in STR.

Explanation:

An anagram of a string is another string that contains the same characters, just rearranged. For instance, 'SILENT' and 'LISTEN' are anagrams of each other, while 'ABA' and 'ABB' are not.

Input:

The first line of input includes an integer 'T', the number of test cases. Each test case consists of: - A line with two space-separated integers N and M, where N is the length of STR and M is the length of PTR. - A line containing the string STR. - A line containing the string PTR. 

Output:

For each test case, provide a sequence of all starting indices of the anagram substrings found in STR. Each test case's output should be on a new line.

Example:

Input: T = 1, N = 8, M = 3, STR = ACDBACDACB, PTR = ABC 
Output: [3, 5, 6]
Explanation: 'BAC', 'CAB', and 'CAB' starting at positions 3, 5, and 6, respectively, are anagrams of 'ABC'.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 105
  • 1 <= M <= N
  • STR and PTR consist only of uppercase English letters.
  • Time limit: 1 second

Note:

Return the indices in ascending order. If no anagram is found, provide an empty sequence.
AnswerBot
4d

Identify all starting indices of anagrams of a given string in another string.

  • Iterate through the main string using a sliding window approach.

  • Use a hashmap to keep track of characters in the anagram s...read more

Help your peers!
Add answer anonymously...
Snapdeal Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter