Find the Occurrence of First Almost Equal Substring Problem
Description
LeetCode Problem 3303.
You are given two strings s and pattern.
A string x is called almost equal to y if you can change at most one character in x to make it identical to y.
Return the smallest starting index of a substring in s that is almost equal to pattern. If no such index exists, return -1.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "abcdefg", pattern = "bcdffg"
Output: 1
Explanation:
The substring s[1..6] == "bcdefg" can be converted to "bcdffg" by changing s[4] to "f".
Example 2:
Input: s = "ababbababa", pattern = "bacaba"
Output: 4
Explanation:
The substring s[4..9] == "bababa" can be converted to "bacaba" by changing s[6] to "c".
Example 3:
Input: s = "abcd", pattern = "dba"
Output: -1
Example 4:
Input: s = "dde", pattern = "d"
Output: 0
Constraints:
1 <= pattern.length < s.length <= 10^5sandpatternconsist only of lowercase English letters.
Follow-up: Could you solve the problem if at most k consecutive characters can be changed?
Solution
Approach: Z-function on the prefix and the suffix
A window of s is almost equal to pattern when it differs from it in at most one position. Comparing every window character by character costs O(nm), which is too slow.
If there is at most one mismatch, a matching prefix of the window and a matching suffix of the window together cover everything except possibly one character. So for a start index i, let pre be the length of the longest common prefix of s[i:] and pattern, and suf the length of the longest common suffix of s[:i+m] and pattern. The window is almost equal exactly when pre + suf >= m - 1.
Both values for every i come from Z-functions: run it on pattern + "#" + s for the prefixes, and on the reversed strings joined the same way for the suffixes. Return the smallest i that passes the test, or -1.
Complexity: O(n + m) time and O(n + m) space, where n and m are the lengths of s and pattern.
class Solution:
def minStartingIndex(self, s: str, pattern: str) -> int:
def z_function(t: str) -> List[int]:
n = len(t)
z = [0] * n
l = r = 0
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l])
while i + z[i] < n and t[z[i]] == t[i + z[i]]:
z[i] += 1
if i + z[i] > r:
l, r = i, i + z[i]
return z
n, m = len(s), len(pattern)
zp = z_function(pattern + "#" + s)
zs = z_function(pattern[::-1] + "#" + s[::-1])
for i in range(n - m + 1):
pre = zp[m + 1 + i]
suf = zs[m + 1 + n - (i + m)]
if pre + suf >= m - 1:
return i
return -1