Accel Thinking

CP Weekly Challenges

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

Walkthrough of CCC 2020 S3 Searching for Strings: slide a fixed window, compare 26-letter frequency signatures, and deduplicate matching substrings with a set. Includes exact and double-hash Python solutions, C++17, proof, and pitfalls.

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

What to Study Next

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

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

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

Therefore len(seen) is exactly the requested count.

Complexity Analysis

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?