To solve this problem efficiently, especially given the large constraints (s and pattern can be up to (3 \times 10^5) characters long), we can utilize the Fast Fourier Transform (FFT) for pattern matching with at most one mismatch. Here's a step-by-step explanation of the approach:
Approach:
-
Hamming Distance Calculation:
- The goal is to find a window in
s that has a Hamming distance (number of differing characters) of at most 1 compared to the pattern.
- A naive approach would involve checking each possible window, leading to a time complexity of (O(n \times m)), which is too slow for large inputs.
-
Optimizing with FFT:
- Character-wise Matching:
- For each character from 'a' to 'z', create two binary arrays:
- Array A: Marks positions in
s where the character appears.
- Array B: Marks positions in
pattern where the character appears.
- Reverse Array B to prepare for convolution.
- Convolution:
- Perform convolution of Array A and Array B using FFT. The result at position
i indicates how many times the character matched at that specific offset.
- Sum the convolution results for all characters to get the total number of matches for each possible window.
- Mismatch Calculation:
- For each window, calculate the number of mismatches by subtracting the number of matches from the pattern length.
- Identify the smallest index where mismatches are ≤ 1.
-
Implementation Considerations:
- Implementing FFT efficiently is crucial. The provided implementation uses the Cooley-Turkey FFT algorithm with complex numbers.
- Ensure that the FFT and inverse FFT are correctly implemented to avoid precision errors.
- Optimize memory usage by preallocating arrays and reusing them when possible.
C++ Implementation:
Below is the complete C++ implementation encapsulating the above approach. The Solution class contains the minStartingIndex method, which returns the smallest starting index of a substring in s that is almost equal to pattern. If no such index exists, it returns -1.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef complex<double> cd;
const double PI = acos(-1.0);
// FFT function: Cooley-Turkey FFT (in-place, breadth-first)
void fft(vector<cd> & a, bool invert) {
int n = a.size();
// Bit-reversal permutation
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]);
}
// Cooley-Turkey
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(vector<double> a, vector<double> b){
int n=1;
while(n < a.size() + b.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(a.size() + b.size() -1, 0);
for(int i=0;i<result.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 total_matches array
int size = n - m +1;
vector<long long> total_matches(size, 0);
// For each character 'a' to 'z'
for(char c = 'a'; c <= 'z'; c++){
// Create binary vectors for s and pattern
vector<double> A(n, 0.0);
vector<double> B(m, 0.0);
for(int i=0;i<n;i++) if(s[i] == c) A[i] = 1.0;
for(int i=0;i<m;i++) if(pattern[i] == c) B[m -1 -i] =1.0; // reversed
// Perform convolution
vector<long long> conv = multiply(A, B);
// Add matches to total_matches
// conv size is n + m -1
for(int i=0;i < size; i++){
if(i + m -1 < conv.size())
total_matches[i] += conv[i + m -1];
}
}
// Now, for each window, compute mismatches
// mismatches = m - matches
for(int i=0;i< size; i++){
long long mismatches = m - total_matches[i];
if(mismatches <=1){
return i;
}
}
return -1;
}
};
Explanation:
-
FFT Implementation:
- The
fft function performs the Fast Fourier Transform on a vector of complex numbers. It can perform both forward and inverse FFT based on the invert flag.
- The
multiply function uses the FFT to perform polynomial multiplication (convolution) of two real-valued vectors a and b. It returns the resulting convolution as a vector of long longs.
-
Main Logic in minStartingIndex:
- Total Matches Calculation:
- For each character
c from 'a' to 'z', binary vectors A and B are created where A[i] is 1 if s[i] == c, else 0. Similarly, B[i] is 1 if pattern[i] == c, else 0. Note that B is reversed to align correctly for convolution.
- Perform convolution between
A and reversed B. The result at position i + m - 1 indicates how many times character c matched in the window starting at index i.
- Sum these results across all characters to get
total_matches[i] for each window starting at i.
- Mismatch Check:
- For each window starting at
i, calculate the number of mismatches as m - total_matches[i].
- If the number of mismatches is ≤ 1, return the current index
i as it's the smallest such index.
- Return -1 if No Valid Window Found:
- If no window satisfies the condition, return
-1.
Time Complexity:
- The overall time complexity is (O(26 \times n \log n)), which is efficient given the constraints ((n \leq 3 \times 10^5)).
Space Complexity:
- The space complexity is (O(n)), used primarily by the FFT buffers and intermediate vectors.
Usage:
To use the Solution class, create an instance and call the minStartingIndex method with the strings s and pattern. For example:
int main(){
Solution sol;
string s = "abcdefg";
string pattern = "bcdffg";
cout << sol.minStartingIndex(s, pattern); // Output: 1
}
This will output 1, as explained in the first example of the problem statement.