Skip to content
BytePatterns

How Often Each Prefix Appears

HardStrings#z-algorithm#suffix-sums~40m

Problem

Given a string s of length n, return a list of n counts where the entry at index i - 1 says how many times the prefix of s with length i appears inside s. Overlapping appearances count separately, and the prefix itself counts as one. The answer should take O(n) time, so searching for each prefix separately is too slow.

Examples

Input:  s = "abacaba"
Output: [4, 2, 2, 1, 1, 1, 1]
Why:    "a" appears 4 times, "ab" and "aba" twice each, longer prefixes once
Input:  s = "aaa"
Output: [3, 2, 1]
Why:    the two appearances of "aa" overlap and both count
Input:  s = ""
Output: []
Why:    edge case, there are no prefixes to count

Hints

0 / 3

Stuck on the idea rather than the code? Z-Algorithm Intuition covers it.