#438
Medium Algorithms Find all anagrams in a string
Hash Table String Sliding Window
53.3% acceptance
Jan 13, 2026
13157
375
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_anagrams(s: String, p: String) -> Vec<i32> {
let mut result = Vec::new();
let s_bytes = s.as_bytes();
let p_bytes = p.as_bytes();
if s.len() < p.len() {
return result;
}
let mut p_count = vec![0; 26];
let mut window_count = vec![0; 26];
for &b in p_bytes {
p_count[(b - b'a') as usize] += 1;
}
for i in 0..s_bytes.len() {
window_count[(s_bytes[i] - b'a') as usize] += 1;
if i >= p.len() {
let remove_idx = i - p.len();
window_count[(s_bytes[remove_idx] - b'a') as usize] -= 1;
}
if i + 1 >= p.len() && window_count == p_count {
result.push((i + 1 - p.len()) as i32);
}
}
result
}
}