LeetCode 438: Find All Anagrams in a String Solution
Master LeetCode problem 438 (Find All Anagrams in a String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
438. Find All Anagrams in a String
Problem Explanation
Explanation
To solve this problem, we can use a sliding window approach. We will maintain a frequency map for the characters in string p, and then slide a window of length p.length() over string s, updating the frequency map accordingly. If the frequency map matches the frequency map of string p, we have found an anagram at the current window position. We can keep track of the start indices of such anagrams.
- Initialize two frequency arrays, one for string
pand one for the sliding window in strings. - Slide the window over string
s, updating the frequency arrays. - If the frequency arrays match, add the start index of the window to the result.
- Return the list of start indices where anagrams of
pare found ins.
Time Complexity: O(n), where n is the length of string s.
Space Complexity: O(1) since the frequency map will have at most 26 characters.
Solution Code
import java.util.*;
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
int[] pFreq = new int[26];
int[] sFreq = new int[26];
for (char c : p.toCharArray()) {
pFreq[c - 'a']++;
}
int pLength = p.length();
for (int i = 0; i < s.length(); i++) {
sFreq[s.charAt(i) - 'a']++;
if (i >= pLength) {
sFreq[s.charAt(i - pLength) - 'a']--;
}
if (Arrays.equals(pFreq, sFreq)) {
result.add(i - pLength + 1);
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 438 (Find All Anagrams in a String)?
This page provides optimized solutions for LeetCode problem 438 (Find All Anagrams in a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 438 (Find All Anagrams in a String)?
The time complexity for LeetCode 438 (Find All Anagrams in a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 438 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 438 in Java, C++, or Python.