1457. Pattern Sighting Odds
A lab records a stream of random symbols produced by a noisy sensor. Each symbol is picked independently and uniformly from the first alphabet lowercase letters, and exactly length symbols are recorded. Engineers want to know how likely it is that the recorded string contains the given pattern as a contiguous substring somewhere. Return that probability as a real number between 0 and 1. The pattern uses only the first alphabet letters, and a string shorter than the pattern can never contain it. An absolute error of 1e-6 is accepted. Track matching progress with a prefix-function automaton, for O(length * |pattern| * alphabet) time and O(|pattern| * alphabet) space.
Example 1
- Input:
- pattern = "ab", length = 3, alphabet = 2
- Output:
- 0.5
- Explanation:
Of the 8 strings over {a, b} of length 3, exactly aab, aba, abb and bab contain "ab", giving 4/8.
Example 2
- Input:
- pattern = "aa", length = 4, alphabet = 2
- Output:
- 0.5
- Explanation:
Exactly 8 of the 16 binary strings of length 4 contain "aa", so the probability is one half.
Example 3
- Input:
- pattern = "abc", length = 2, alphabet = 3
- Output:
- 0
- Explanation:
A string of length 2 is too short to contain a pattern of length 3, so the probability is 0.
Constraints
1 ≤ pattern.length ≤ 100
1 ≤ length ≤ 1000; 1 ≤ alphabet ≤ 26
pattern uses only the first alphabet lowercase letters. Absolute error 1e-6.
How this problem is judged
- Answers
- Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
- Tolerance
0.000001
Expected complexity
- Time
- O(length * |pattern| * alphabet)
- Space
- O(|pattern| * alphabet)