C++ 0438.cpp
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.size() < p.size())
return {};
vector<int> result;
vector<short> hp(32, 0);
for (auto c : p)
hp[c - 'a']++;
vector<short> h2(32, 0);
for (int i = 0; i < p.size(); i++)
h2[s[i] - 'a']++;
if (hp == h2)
result.push_back(0);
for (int i = 1; i + p.size() <= s.size(); i++)
{
auto remove = s[i - 1];
h2[remove - 'a']--;
h2[s[i + p.size() - 1] - 'a']++;
if (hp == h2)
result.push_back(i);
}
return result;
}
};
Difficulty
and has an acceptance rate of about 54% (2+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic “find all anagrams of a pattern in a text” problem using a sliding-window technique. It first builds a frequency histogram for the pattern, then maintains a matching histogram for the current window of the text. Whenever the two histograms are identical, the start index of the window is recorded. The algorithm works entirely with fixed-size arrays of primitive types, which keeps the runtime tight and the memory footprint small.
Building the pattern histogram
The code creates a vector of 32 short elements, enough to hold counts for each lowercase letter. It then iterates over the pattern string and increments the corresponding slot.
vector<short> hp(32, 0);
for (auto c : p)
hp[c - 'a']++;
This step establishes the reference distribution of characters that any anagram must match.
Initial window preparation
Before sliding, the algorithm prepares the histogram for the first window whose length equals the pattern. It again uses a 32-element vector and increments counts for the first p.size() characters of the text.
vector<short> h2(32, 0);
for (int i = 0; i < p.size(); i++)
h2[s[i] - 'a']++;
If the two histograms are already equal, the starting index 0 is added to the result list.
if (hp == h2)
result.push_back(0);
Sliding the window
The core loop moves the window one character to the right on each iteration. The character that leaves the window has its count decremented, while the newly entered character has its count incremented. After the update, a direct comparison of the two histograms determines whether the current window forms an anagram.
for (int i = 1; i + p.size() <= s.size(); i++)
{
auto remove = s[i - 1];
h2[remove - 'a']--;
h2[s[i + p.size() - 1] - 'a']++;
if (hp == h2)
result.push_back(i);
}
The loop condition i + p.size() <= s.size() guarantees that the window never exceeds the bounds of the text.
Edge-case handling
The function begins with a guard that immediately returns an empty vector when the text is shorter than the pattern. This prevents any out-of-range accesses in the subsequent histogram construction.
if (s.size() < p.size())
return {};
When the pattern is empty, the initial histogram hp remains all zeros. The first comparison succeeds, inserting index 0. The sliding loop then runs for every possible start position, each iteration effectively performing a no-op update (decrement followed by increment of the same character). Consequently, the result contains every index from 0 through s.size(), which is the mathematically correct set of anagram positions for an empty pattern.
If the text itself is empty while the pattern is non-empty, the guard again returns an empty result, handling the situation without entering any loops.
Performance-focused choices
The implementation deliberately uses a fixed-size vector of short rather than a map or a larger container. This choice yields constant-time access for character counts and reduces cache pressure. Because the alphabet size is limited to 26 letters, the extra six slots in the 32-element vector do not affect correctness but keep the underlying memory layout aligned to typical word boundaries, which can improve memory throughput.
Comparing the two histograms with the == operator leverages the fact that the vectors have a known small size; the comparison iterates over at most 32 elements, which is effectively constant work per window shift. This avoids the need for a separate mismatch counter or more complex data structures.
The sliding-window update touches only two positions in the histogram per iteration-one decrement and one increment-so the per-step work does not depend on the pattern length. This design ensures that the overall execution time scales linearly with the length of the text while keeping the inner loop extremely lightweight.
Result construction
All matching start indices are accumulated in a vector<int> named result. The function returns this vector directly, allowing the caller to obtain the complete list of anagram positions without additional processing. The use of push_back ensures that the result grows only as needed, avoiding preallocation overhead.
ELI5 - Simplified Explanation
Imagine a long train made of colorful letter blocks. You are looking for a specific pattern of letters hidden somewhere inside that train.
First, look at the pattern you want to find. Count how many of each letter are in that small set and keep a tally on a piece of paper. Now, look at the very front part of the long train. Count the letters there and keep a tally for those too. If the tally for the front part of the train matches the tally for the pattern you want, then that spot is a match.
Now comes the fun part. Imagine you have a sliding window that covers the same number of train cars as the pattern. Instead of counting all the train cars again, slide the window one step to the right. When you slide, one car falls off the back and a new car appears at the front. Update your tally by taking one away for the car that left and adding one for the new car that arrived. Every time you slide, compare the new tally with the original pattern tally. If they look exactly the same, you have found the pattern hiding in the train. Keep doing this until you have checked all the way to the end of the train.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | C# | Python | Go | Rust | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | begeekmyfriend | C | |||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 242: Valid Anagram
- problem 567: Permutation in String
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality