To solve this problem, we need to efficiently find the smallest starting index of a substring in s that is "almost equal" to pattern. A substring is almost equal to the pattern if we can change at most one character in the substring to make it identical to the pattern.
Given the constraints (1 <= pattern.length < s.length <= 10^5), a brute-force approach that checks each possible substring and counts the differences would be too slow, with a time complexity of O(N * M), where N is the length of s and M is the length of pattern. Instead, we'll use an optimized approach based on the Fast Fourier Transform (FFT) to perform convolutions, which allows us to compute the number of matching characters between the substring and the pattern efficiently.
Approach:
-
Convolution with FFT:
- For each character
c in the alphabet (a-z), we'll create two binary arrays:
- A[c]: An array where
A[c][i] = 1 if s[i] == c, otherwise 0.
- B[c]: An array where
B[c][i] = 1 if pattern[m - 1 - i] == c, otherwise 0. Notice that the pattern is reversed for the convolution process.
- Perform a convolution between
A[c] and B[c] for each character c. The result of this convolution tells us how many times character c matches at each possible window of the substring in s.
- Sum the results of all convolutions to get the total number of matching characters for each window.
-
Determine Differences:
- For each window of length
m in s, calculate the number of differences by subtracting the number of matching characters from m.
- If the number of differences is
<= 1, return the starting index of this window.
-
Edge Cases:
- If the length of
pattern is greater than s, return -1 immediately.
- Ensure that the FFT is implemented correctly to handle floating-point inaccuracies by rounding appropriately.
Implementation:
Below is the complete C++ implementation using the described approach. This solution includes an FFT-based convolution function tailored for this problem. The minStartingIndex function applies the convolution method to find the smallest starting index where the substring is almost equal to the pattern.
#include <bits/stdc++.h>
using namespace std;
typedef complex<double> cd;
const double PI = acos(-1);
// Fast Fourier Transform implementation
void fft(vector<cd> & a, bool invert) {
int n = a.size();
// Bit reversal
for(int i=1,j=0;i<n;i++) {
int bit = n >> 1;
while(j >= bit) {
j -= bit;
bit >>=1;
}
if(j < bit) j += bit;
if(i < j) swap(a[i], a[j]);
}
// FFT
for(int len=2; len<=n; len <<=1){
double angle = 2 * PI / len * (invert ? -1 : 1);
cd wlen(cos(angle), sin(angle));
for(int i=0; i<n; i += len){
cd w(1);
for(int j=0; j<len/2; ++j){
cd u = a[i+j];
cd v = a[i+j + len/2] * w;
a[i+j] = u + v;
a[i+j + len/2] = u - v;
w *= wlen;
}
}
}
if(invert){
for(auto & x: a) x /= n;
}
}
// Function to perform convolution using FFT
vector<long long> multiply(const vector<double> & a, const vector<double> & b){
int n =1;
int total_size = a.size() + b.size() -1;
while(n < total_size) n <<=1;
vector<cd> fa(n, 0), fb(n, 0);
for(int i=0;i<a.size(); ++i) fa[i] = a[i];
for(int i=0;i<b.size(); ++i) fb[i] = b[i];
fft(fa, false);
fft(fb, false);
for(int i=0;i<n;i++) fa[i] *= fb[i];
fft(fa, true);
vector<long long> result(total_size, 0);
for(int i=0;i<total_size;i++) {
result[i] = round(fa[i].real());
}
return result;
}
class Solution {
public:
int minStartingIndex(string s, string pattern) {
int n = s.size();
int m = pattern.size();
if(m > n) return -1;
// Initialize matches array
// Size needed is n + m -1
vector<long long> matches(n + m -1, 0);
// For each character 'a' to 'z', perform convolution
for(char c = 'a'; c <= 'z'; c++){
// Build A[c]
vector<double> A;
A.reserve(n);
for(int i=0;i<n;i++) A.push_back(s[i] == c ? 1.0 : 0.0);
// Build B[c], reversed
vector<double> B;
B.reserve(m);
for(int i=m-1;i>=0;i--) B.push_back(pattern[i] == c ?1.0 :0.0);
// Perform convolution
vector<long long> C = multiply(A, B);
// Accumulate the matches
for(int i=0;i<C.size();i++) {
matches[i] += C[i];
}
}
// Iterate over all possible windows
for(int j=0; j <= n -m; j++){
// The window ending at j +m -1
int window_end = j +m -1;
if(window_end >= matches.size()) continue;
long long num_matches = matches[window_end];
long long differences = m - num_matches;
if(differences <=1){
return j;
}
}
return -1;
}
};
Explanation of the Code:
-
FFT and Convolution:
- The
fft function performs the Fast Fourier Transform on a vector of complex numbers. It can perform both the forward and inverse FFT based on the invert flag.
- The
multiply function takes two vectors of doubles, performs FFT on both, multiplies them point-wise in the frequency domain, and then performs an inverse FFT to obtain the convolution result.
-
Main Logic (minStartingIndex Function):
- For each character
c from 'a' to 'z':
- Create binary arrays
A[c] for string s and B[c] for the reversed pattern.
- Perform convolution between
A[c] and B[c] to find matches of character c.
- Accumulate the convolution results into the
matches array to keep track of the total number of matching characters for each window.
- After processing all characters, iterate through each possible starting index
j for the window in s:
- Calculate the number of differences by subtracting the number of matches from the length of the pattern.
- If the number of differences is
<= 1, return the current starting index j.
- If no such window is found, return
-1.
Complexity Analysis:
-
Time Complexity:
- The FFT-based convolution runs in O(N log N) time for each character, where N is the size of the vectors being convolved. Since there are 26 characters, the overall time complexity is O(26 * N log N), which simplifies to O(N log N).
-
Space Complexity:
- The space required is O(N) for each convolution and the
matches array, leading to an overall space complexity of O(N).
This solution efficiently handles the large input sizes by leveraging the power of FFT-based convolution, ensuring that the solution runs within acceptable time and space limits.