
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].
- We need to find anagrams of "ab" in "abab".
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].
- We need to find anagrams of "abc" in "abcab".
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
Editorial
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. |
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