1212. Prefix Echo Counts

A text-compression tool wants to know how often each opening fragment of a string reappears inside it. Given a lowercase string s of length n, for every length L from 1 to n look at the prefix s[0..L) and count how many times it occurs as a substring of s. Occurrences may overlap, and the prefix itself is one occurrence. For aaa the prefix a occurs 3 times, aa twice and aaa once.

Return an array of n integers where entry L-1 is the count for length L. A solution based on the prefix function runs in O(n) time and O(n) space, while counting each prefix separately is quadratic.

Example 1

Input:
s = "aaa"
Output:
[3,2,1]
Explanation:

The prefixes a, aa, aaa occur 3, 2 and 1 times, giving [3,2,1].

Example 2

Input:
s = "abab"
Output:
[2,2,1,1]
Explanation:

Prefixes a and ab each occur twice, while aba and abab occur once, giving [2,2,1,1].

Example 3

Input:
s = "abc"
Output:
[1,1,1]
Explanation:

Every prefix occurs exactly once, giving [1,1,1].

Constraints

1 ≤ s.length ≤ 2 * 105

s contains only lowercase letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…