progress

~/problems / String hashing

Counting phrases on a ticker tape

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A newsroom's ticker tape is one long string. Editors hand you phrases, all of length k, and want each one's count on the tape. Overlaps count: "aa" appears 3 times in "aaaa".

Write count_phrases(tape: str, phrases: list[str]) -> list[int], counts in the order of phrases.

count_phrases("abababa", ["aba", "bab", "abb"])   # [3, 2, 0]
count_phrases("aaaa", ["aa", "aa"])                # [3, 3]   (the same phrase can be asked twice)
count_phrases("hi", ["hello"])                     # [0]      (longer than the tape)

Tape up to 200,000 characters; up to 50 phrases, total length at most 200,000; any characters.

⭐ Bonus: slicing every window or comparing each phrase at every position still passes; a speed test with k in the tens of thousands earns a star at about O(len(tape) + total phrase length).

Show hint

fingerprint each length-k window with a rolling hash updated in O(1) per slide (B = 131, M = 2**61 - 1 as in Basics: prefix hashes for O(1) substring comparison; in C++ or Java two moduli near 10^9 avoid 128-bit products), count fingerprints in a dict, and look up each phrase's.

Topic: String hashing / Rabin-Karp. Rolling polynomial hash for O(1) substring comparison.

0:00
Ctrl ' run · Ctrl ↵ submit
esc