Given two strings — a needle and a haystack — count how many distinct permutations of the needle appear as substrings of the haystack. CCC 2020 Senior Problem 3, Searching for Strings, sets two traps: enumerating the needle’s permutations is factorial and hopeless, and a sliding window that finds matches must not count repeats twice. The full solution assigns one job to each of three structures: a sliding window scans, a frequency signature tests “is this a permutation”, and a set tests “have we seen this one”. Separating the two kinds of “equal” is the whole point.
Where This Fits in the CCC DSA Map
- Level: Senior S3
- Pattern: Sliding Window + Frequency Signature + Set Deduplication
- Prerequisite: arrays and string indexing, list comparison, sets (Python string slicing, Python list fundamentals)
- What this teaches: split “count equality” (anagram test) from “identity equality” (deduplication) into two steps with one structure each; signature + set is the reusable skeleton for string counting problems
- Where it appears again: the sliding-window topic
DSA-TOPIC-003(planned), CPW-004 Sunny Days (published prefix/sliding-window cousin), and the hashing sessions of the same notebook (Nailed It is its sibling)
What to Study Next
- Related CP Weekly problems: CCC 2025 J4 Sunny Days (sliding window and prefix counting), CCC 2017 J5/S3 Nailed It! (counting with complement pairs), CPW-009 Good Groups
- Related Python / C++ foundations: Python String Slicing (left-closed right-open windows), Python Lists: append() vs +
- Related DSA roadmap article:
DSA-TOPIC-003Prefix Sum and Sliding Window Patterns (planned)
What the Problem Is Asking
The first line is the needle N, the second the haystack H, both lowercase, 1 ≤ |N|, |H| ≤ 200,000. Count the distinct permutations of N that occur as substrings of H at least once; repeated occurrences of the same permutation count once.
Official sample: N = aab, H = abacabaa → output 2: aba and baa appear (aba twice, still one), aab never appears.
Where Beginners Often Get Stuck
- Enumerating permutations: |N| up to 200,000 makes the factorial astronomic; “
aabhas only 3” is luck, not an algorithm. - Sliding without dedup:
abaappears twice in the sample; counting windows gives 3 matches, the answer is 2 — repeats must merge. - Dedup without the signature test: stuffing every length-k substring into a set happens to give the right count but uses nothing about the needle, and breaks under any “must be an anagram” variant.
- Hash-only sets: storing polynomial fingerprints throws the strings away; two distinct strings with the same hash are merged (the notebook’s words: a set of only fingerprints cannot compare real strings after a collision).
- Ignoring
k > n: when the needle is longer than the haystack, output 0.
Core Algorithm Idea
A permutation is exactly the same character multiset: aab, aba, baa are all “two a’s, one b”. So “is this window a permutation of the needle” becomes “do the window’s 26 letter counts equal the needle’s” — a signature.
Scan with a sliding window: fixed length k = |N|, each step adds one character on the right and removes one on the left, maintaining the window counts in O(1). Each complete window costs an O(26) signature comparison.
A passed test still does not count immediately — the matching window’s substring goes into a set: sets deduplicate natively, and the final set size is the answer. This separates two equalities: the signature answers “is it a permutation”, the set answers “is it a new one”.
The notebook’s full trace (N=aab, H=abacabaa):
| Start | Window | Counts (a,b,c) | Match? | Set |
|---|---|---|---|---|
| 0 | aba | 2,1,0 | yes | {aba} |
| 1 | bac | 1,1,1 | no | {aba} |
| 2 | aca | 2,0,1 | no | {aba} |
| 3 | cab | 1,1,1 | no | {aba} |
| 4 | aba | 2,1,0 | yes | {aba} (dup) |
| 5 | baa | 2,1,0 | yes | {aba, baa} |
Answer 2.
State / Data Structure Design
target[26]: the needle’s letter counts (target signature).window[26]: the current window’s counts, updated in O(1) while sliding.seen: the set of confirmed matching substrings.k = len(N): the fixed window size.
Algorithm Steps
- Read N and H; if
|N| > |H|, print 0. - Count the needle into
target. - Slide over H: add the right character; once the index ≥ k, remove the character leaving the window.
- For every complete window (index ≥ k−1): if
window == target, add the substring toseen. - Print
len(seen).
Sample Check with the Official Data
The notebook trace checks out cell by cell: aba at starts 0 and 4 counts once, baa at start 5 is the second distinct permutation → output 2. Four more checks: N=ab, H=baba → 2; N=abc, H=def → 0; N=aaaa, H=aaa → 0 (k > n); N=aa, H=aaaa → 1 (repeated identity counts once).
Python Solution
needle = input().strip()
haystack = input().strip()
k = len(needle)
if k > len(haystack):
print(0)
else:
target = [0] * 26
window = [0] * 26
for ch in needle:
target[ord(ch) - ord('a')] += 1
seen = set()
for i, ch in enumerate(haystack):
window[ord(ch) - ord('a')] += 1
if i >= k:
window[ord(haystack[i - k]) - ord('a')] -= 1
if i >= k - 1 and window == target:
start = i - k + 1
seen.add(haystack[start:start + k])
print(len(seen))
This matches the curriculum notebook (p2005 answers cell 4) line for line. Two details: compare signatures as 26-item lists, not Counter — subtraction leaves zero-count entries that can poison == (this package’s own test harness stepped on that); and matched windows go into the set as substrings, not count tuples — the dedup key must be identity.
C++ Solution
#include <iostream>
#include <vector>
#include <string>
#include <set>
using namespace std;
int main() {
string needle, haystack;
cin >> needle >> haystack;
int k = (int)needle.size();
if (k > (int)haystack.size()) {
cout << 0 << '\n';
return 0;
}
vector<int> target(26, 0);
vector<int> window(26, 0);
for (char ch : needle) {
target[ch - 'a']++;
}
set<string> seen;
for (int i = 0; i < (int)haystack.size(); i++) {
window[haystack[i] - 'a']++;
if (i >= k) {
window[haystack[i - k] - 'a']--;
}
if (i >= k - 1 && window == target) {
int start = i - k + 1;
seen.insert(haystack.substr(start, k));
}
}
cout << seen.size() << '\n';
return 0;
}
Mirrors the curriculum C++ reference (answers cell 5); window == target on vector<int> compares lexicographically over a constant 26 items.
Advanced: The Double-Hash Version and Its Price
The exact version copies each matching substring into the set. That is fine for most data (see qa.md for measurements at |H|=200,000), but adversarial inputs — say the needle and haystack are one repeated character — copy O(k) characters per match for O(|H|) matches, totaling O(|H|·k). The notebook’s upgrade (answers cell 13): a sliding window maintaining two polynomial hashes (two moduli), with (hash1 << 32) | hash2 stored in the set — every step O(1), string copies gone. The price is one more assumption: distinct strings must not collide. In contests, dual 64-bit / dual-modulus collision probability is negligible, but know the difference: the exact version is unconditionally correct, the hash version trades a negligible probability for speed. solution_hash.py in this package is the reference.
Why the Algorithm Is Correct
- The signature test is exact: equal 26-way letter counts, item by item, hold if and only if the window is a permutation of the needle (equal multisets ⇔ permutations of each other).
- The sliding signature is maintained correctly: adding the right character and subtracting the leaving one transforms the old window’s counts into the new window’s counts; by induction every complete window’s counts are correct.
- The set dedups correctly: each matching window enters the set under its own identity; repeated occurrences of one permutation stay single, so the set size is the number of distinct permutations.
- No candidate is missed: every length-k substring is visited exactly once by the window.
Therefore len(seen) is exactly the requested count.
Complexity Analysis
- Exact version: time O(|H|·26) for signature comparisons plus string copies on matches (usually far below |H|; adversarial worst O(|H|·k)); space O(26 + total length of distinct matches).
- Double-hash version: time O(|H|), space O(|H|) (set size bound).
- Measured on this machine (|H| = 200,000, small alphabet, many matches): C++ 0.04s, CPython exact 0.26s, double-hash 0.35s — all comfortably inside the CCC 5-second limit; for extreme data prefer C++ or the double-hash build.
Common Mistakes
- Generating all permutations: factorial; even |N| = 11 is too much.
- Counting repeats:
abatwice is still one permutation; dedup by substring identity. Counterequality: zero-count leftovers from subtraction can poison==; use 26-item lists.- Hash-only sets: a collision merges distinct permutations; either store strings or understand the dual-hash assumption.
- Missing
k > n: when the needle is longer, the answer is 0, not “not found”.
Review Questions
- Why is “equal counts” necessary and sufficient for “permutations of each other”? Give an example where counts match but the strings differ.
abaappears twice in the sample but counts once — how would the answer change ifseenwere a list? Use the trace table.- The double-hash version trades certainty for probability: what data breaks a single modulus most easily, and why is dual-modulus far more reliable?
- If the task became “count all occurrence positions” (no dedup), which structure could be removed and how would complexity change?
- With |N| = |H| = 200,000 and the two strings identical, where does the time gap between the exact and double-hash versions come from?
Questions or feedback?
Have a question about this article or want to suggest an improvement? Send us an email.
