CCC 2020 S3 Searching for Strings Solution: Sliding Window, Frequency Signature, Set Deduplication



☰

Start NorthStar

CP Weekly Challenge

CCC 2020 S3 Searching for Strings Solution: Sliding Window, Frequency Signature, Set Deduplication

Use a fixed sliding window and a 26-letter frequency signature, then deduplicate matching permutations with a set.

竞赛编程每周挑战

CCC 2020 S3 Searching for Strings 题解:滑窗 + 频率签名 + 集合去重,分清两种“相等”

用固定滑窗和 26 项频率签名判定排列,再用集合对匹配结果去重。

Share this article

Copy the link, open your phone share sheet, scan the QR code for WeChat, or send by email.




Email

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 (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, in production review), CPW-009 Good Groups
  • Related Python / C++ foundations: Python String Slicing (left-closed right-open windows), Python Lists: append() vs +
  • Related DSA roadmap article: Prefix 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; "aab has only 3" is luck, not an algorithm.
  • Sliding without dedup: aba appears 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

  1. Read N and H; if |N| > |H|, print 0.
  2. Count the needle into target.
  3. Slide over H: add the right character; once the index ≥ k, remove the character leaving the window.
  4. For every complete window (index ≥ k−1): if window == target, add the substring to seen.
  5. 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

  1. Generating all permutations: factorial; even |N| = 11 is too much.
  2. Counting repeats: aba twice is still one permutation; dedup by substring identity.
  3. Counter equality: zero-count leftovers from subtraction can poison ==; use 26-item lists.
  4. Hash-only sets: a collision merges distinct permutations; either store strings or understand the dual-hash assumption.
  5. Missing k > n: when the needle is longer, the answer is 0, not "not found".

Review Questions

  1. Why is "equal counts" necessary and sufficient for "permutations of each other"? Give an example where counts match but the strings differ.
  2. aba appears twice in the sample but counts once — how would the answer change if seen were a list? Use the trace table.
  3. The double-hash version trades certainty for probability: what data breaks a single modulus most easily, and why is dual-modulus far more reliable?
  4. If the task became "count all occurrence positions" (no dedup), which structure could be removed and how would complexity change?
  5. With |N| = |H| = 200,000 and the two strings identical, where does the time gap between the exact and double-hash versions come from?

给两个字符串:needle 和 haystack。问 needle 的多少个不同排列,作为子串在 haystack 里出现过。CCC 2020 Senior 第 3 题 Searching for Strings traps 两层:直接枚举 needle 的排列是 |N|! 级别,不可行;而滑窗找到了匹配,重复出现时又不能重复计数。这题的完整解法是三个数据结构各司其职:滑动窗口负责扫描,频率签名负责判定"是不是排列",集合负责判定"见没见过"。把两种"相等"分开,是整道题的题眼。

本题在 CCC DSA 地图里的位置

  • Level: Senior S3
  • Pattern: Sliding Window + Frequency Signature + Set Deduplication(滑窗 + 频率签名 + 集合去重)
  • Prerequisite: 数组与字符串下标、列表比较、集合(Python 字符串切片、Python 列表基础)
  • What this teaches: 把"计数相等"(anagram 判定)和"身份相等"(去重)拆成两步,各用一个数据结构;签名 + 集合的组合拳是字符串计数题的通用骨架
  • Where it appears again: 滑窗专题 (planned)、CPW-004 Sunny Days(已发布的前缀/滑窗 cousins)、同教案前两个 Session 的哈希进阶(Nailed It 是姊妹题)

下一步推荐

如果你已经理解这道题,可以继续看:

题目要我们做什么

第一行 needle N,第二行 haystack H,都是小写字母,1 ≤ |N|, |H| ≤ 200,000。统计 N 的不同排列中,有多少个作为子串在 H 中至少出现一次。同一排列出现多次只算一次。

官方样例:N = aab,H = abacabaa → 输出 2:aba 和 baa 都出现(aba 出现两次也只算一种),aab 没出现。

初学者容易卡在哪里

  • 枚举所有排列:|N| 最大 20 万,排列数是天文数字;"aab" 只有 3 种排列是幸运,不能当算法。
  • 只滑窗不去重:aba 在样例中出现两次,数窗口会得到 3 个匹配,答案却是 2——重复匹配必须合并。
  • 只去重不判签名:把所有长度 |N| 的子串直接塞进集合,虽然答案碰巧对(集合天然去重),但完全没有用到 needle 的信息,遇到"必须 anagram"的变体就错;而且这绕过了题目的判定条件。
  • 用哈希就忘了碰撞:只存多项式哈希的集合把原字符串扔了,两个不同串哈希相同会被误判成同一种(教案原话:签名集合只含指纹时无法做碰撞后的真实比较)。
  • 忽略 k > n:needle 比 haystack 长时直接输出 0。

核心算法概念

排列的本质是字符多重集相同:aab、aba、baa 都是"两个 a 一个 b"。所以"窗口是不是 needle 的排列"可以转化为"窗口的 26 项字母计数是否等于 needle 的计数"——这就是一个签名。

扫描用滑动窗口:窗口长度固定 k=|N|,每次右端进一个字符、左端出一个字符,O(1) 维护窗口计数。每个完整窗口花 O(26) 比较一次签名。

判定通过也不立刻计数——先把匹配窗口的原串放进集合:集合天然去重,最后集合大小就是答案。这一步区分了两种相等:签名回答"是不是排列",集合回答"是不是新排列"。

教案完整 trace(N=aab, H=abacabaa):

起点 窗口 计数 (a,b,c) 匹配? 集合
0 aba 2,1,0 是 {aba}
1 bac 1,1,1 否 {aba}
2 aca 2,0,1 否 {aba}
3 cab 1,1,1 否 {aba}
4 aba 2,1,0 是 {aba}(重复,不加)
5 baa 2,1,0 是 {aba, baa}

答案 2。

状态定义

  • target[26]:needle 的字母计数(目标签名)。
  • window[26]:当前窗口的字母计数,随滑窗 O(1) 更新。
  • seen:已确认的匹配子串集合(去重用)。
  • k = len(N):窗口固定长度。

算法步骤

  1. 读入 N、H;若 |N| > |H| 输出 0。
  2. 统计 needle 计数到 target。
  3. 滑窗扫描 H:右端字符计数 +1;下标 ≥ k 时左端出窗字符计数 −1。
  4. 每个完整窗口(下标 ≥ k−1):window == target 则把该子串加入 seen。
  5. 输出 len(seen)。

官方样例核对

教案 trace 表逐格核对(见上表):起点 0、4 的 aba 只计一次,起点 5 的 baa 是第二个新排列,输出 2 ✓。另复核四组:N=ab, H=baba → 2(ba、ab);N=abc, H=def → 0;N=aaaa, H=aaa → 0(k>n);N=aa, H=aaaa → 1(重复身份只计一次)。

Python 解法

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))

要点:代码与课程教案(p2005 answers cell 4)参考实现一致。两个细节:签名比较用26 项列表而不是 Counter——Counter 相减后会保留零计数项,直接 == 可能得到意外结果(本包测试脚本就踩过这个坑);匹配的窗口要把子串本身放进集合,只放计数元组会把"不同排列、相同计数"的错误合并——虽然 anagram 判定已经保证计数相同,但去重的键必须是身份。

C++ 解法

#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;
}

要点:与教案 C++ 参考(answers cell 5)一致。window == target 对 vector<int> 是字典序比较,26 项 O(26) 恒定。

进阶:双哈希版与它的代价

精确版每找到一个匹配要把子串复制进集合。大多数数据没问题(|H|=20 万随机数据实测见 qa.md),但 adversarial 数据(如 needle 和 haystack 全是同一个字符)会让每次插入都复制 O(k) 字符,总代价 O(|H|·k)。教案的进阶做法(answers cell 13):滑动窗口维护双多项式哈希(两个模数),匹配时把 (hash1 << 32) | hash2 存入集合——每步 O(1),把字符串复制的开销消掉。代价是正确性多了一条"不同串不碰撞"的概率假设;竞赛中双 64 位/双模数碰撞概率低到可以忽略,但要明白精确版与哈希版的证明差异:前者无条件正确,后者以可忽略的碰撞概率换速度。本文附 solution_hash.py 供对照。

正确性说明

  • 签名判定完备:窗口与 needle 的字母计数逐项相等,当且仅当窗口是 needle 的一个排列(多重集相等 ⇔ 存在排列关系)。
  • 滑窗维护的签名正确:进窗 +1、出窗 −1 恰好把旧窗口计数变成新窗口计数,归纳可得每个完整窗口的计数都正确。
  • 集合去重正确:每个匹配窗口以其原串身份入集;同一排列多次出现时集合只保留一份,集合大小即不同排列数。
  • 无遗漏:所有长度为 k 的子串都被滑窗恰好访问一次。

因此 len(seen) 就是题目所求。

复杂度分析

  • 精确版:时间 O(|H|·26)(签名比较)+ 匹配插入的字符串复制(通常远小于 |H| 次;adversarial 最坏 O(|H|·k));空间 O(26 + 不同匹配串总长)。
  • 双哈希版:时间 O(|H|),空间 O(|H|)(集合规模上界)。
  • 实测(本机,|H|=20 万、小字母表多匹配):C++ 0.04s、CPython 精确版 0.26s、双哈希版 0.35s——CCC 5 秒时限下三版均轻松通过;极限数据请优先 C++ 或双哈希版。

常见错误

  1. 生成所有排列:|N|! 级别,连 |N|=11 都撑不住。
  2. 重复计数:aba 出现两次算成两种;必须按子串身份去重。
  3. Counter 直接 ==:相减产生的零计数项会干扰比较,用 26 项列表更稳。
  4. 只存哈希不放原串:碰撞会把不同排列误判为同一种;要么存原串,要么明白双哈希的概率假设。
  5. 漏掉 k > n:needle 更长时答案是 0,不是"找不到"。

复习问题

  1. 为什么"计数相等"是"互为排列"的充要条件?举一个计数相同但不是同一个串的例子。
  2. 样例中 aba 出现两次只算一次——如果把 seen 改成列表,答案会变吗?用 trace 表说明。
  3. 双哈希版把正确性换成概率保证:单模数时什么数据最容易让它出错?双模数为什么可靠得多?
  4. 如果题目改成"统计所有出现位置的数量"(不去重),哪个数据结构可以删掉?复杂度怎么变?
  5. |N|=|H|=200,000 且两串完全相同,精确版与双哈希版的时间差别来自哪里?

Questions or feedback?

Have a question about this article or want to suggest an improvement? Send us a private message.

Send Feedback

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

Back to CP Weekly Challenge
返回竞赛编程每周挑战

CP ACADEMY

Not sure which challenges fit your level?

Use the CP assessment to explore your current starting point and choose topics to practise next. You can keep reading and practising without taking an assessment.

60 minutes continuously · Python or C++ · Choose your competition goal

Discover Your CP Level

Scroll to Top