Problem 438

Abstract / Summary

Find all starting indices in a string where an anagram of a given pattern appears as a substring.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
33 lines | 730 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (2+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Sliding Window
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.44 | σ = 0.74

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
51 links | 35 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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