1461. Waiting for the Pattern
A monitoring tool receives one random letter per tick. Each letter is chosen independently and uniformly from the first alphabet lowercase letters, and the tool stops the first time the letters received so far end with the given pattern. Return the expected number of ticks until it stops. That expectation is a rational number, but it always has the form of an integer here: it equals the sum of alphabet^L over every length L from 1 to the pattern length for which the first L letters of pattern equal its last L letters (the full length always counts). Return it modulo 1000000007, using a prefix function in O(|pattern|) time and O(|pattern|) space.
Example 1
- Input:
- pattern = "aa", alphabet = 2
- Output:
- 6
- Explanation:
The borders have lengths 1 and 2, so the expected wait is 2 + 4 = 6 ticks.
Example 2
- Input:
- pattern = "ab", alphabet = 2
- Output:
- 4
- Explanation:
Only the full pattern is its own border, so the expected wait is 2^2 = 4.
Example 3
- Input:
- pattern = "a", alphabet = 1
- Output:
- 1
- Explanation:
With a single letter available the pattern appears after exactly one tick.
Constraints
1 ≤ pattern.length ≤ 105
1 ≤ alphabet ≤ 26; pattern uses only the first alphabet lowercase letters
The result is taken modulo 109 + 7.
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 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms
Expected complexity
- Time
- O(|pattern|)
- Space
- O(|pattern|)