1215. Near-Miss Matches
A spell checker wants to flag every spot in a document that looks almost like a keyword, tolerating a single typo. Given a lowercase string text and a lowercase string pattern of length m, look at every substring of text that has length m. A window is a near miss when it differs from pattern in at most one position, so an exact match also counts.
Return how many start positions of text give a near-miss window. Windows are counted by start position, and overlapping windows are all counted. Comparing every window character by character costs O(n * m); the intended solution uses Z-functions of the forward and reversed strings and runs in O(n + m) time with O(n + m) space.
Example 1
- Input:
- text = "abcabd", pattern = "abc"
- Output:
- 2
- Explanation:
The windows
abc(0 differences) andabd(1 difference) qualify, whilebcaandcabdiffer in 3 places, so the answer is 2.
Example 2
- Input:
- text = "aaaa", pattern = "ab"
- Output:
- 3
- Explanation:
All three windows are
aa, each differing fromabin one place, so the answer is 3.
Example 3
- Input:
- text = "xyz", pattern = "abc"
- Output:
- 0
- Explanation:
Every window differs from
abcin three positions, so the answer is 0.
Constraints
1 ≤ pattern.length ≤ text.length ≤ 2 * 105
both strings contain 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 + m)
- Space
- O(n + m)