diff --git a/String_Algo/Z-Algorithm b/String_Algo/Z-Algorithm new file mode 100644 index 0000000..6e20715 --- /dev/null +++ b/String_Algo/Z-Algorithm @@ -0,0 +1,80 @@ +#include +using namespace std; +#define ll long long +#define ln "\n" +#define pb push_back +#define pll pair +#define ppll pair +#define vll vector +#define vs vector +#define vpll vector +#define vvll vector> +#define vvpll vector +#define f first +#define s second +#define bs binary_search +#define lb lower_bound +#define ub upper_bound +#define Test ll T;cin>>T; while(T--) +#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL); +#define init(x,n,v) for(ll i=0;i<=n;i++) x[i]=v; +#define all(x) x.begin(),x.end() +#define allr(x) x.rbegin(),x.rend() +#define pi 3.14159265358979323846 +#define MOD 998244353 +#define MAX 2000000000000000000 +#define MAXN 100005 + +vector zfunction(string &s){ + + // 0th -index based z-function + // IN z-function at each index we check the longest common prefix between that index and starting point + // we take the z-function of the starting index as 0 + // Here we maintain a segment l to r which are similar to the 0th index to r-l index + // when we are in that segment we don't have to traverse to r because the same answer for corresponding starting element is already known + // we just have to traverse when the common prefix is greater than or equal to the range (r-index) or we are outside the right boundary r + // Time complexity for this algorithm is O(n) and to search a pattern in this we just add that pattern before the main text/array in that case the size become n+m(size of pattern) and complexity goes to O(n+m) + + ll n = s.size(); + vector zarr(n,0); + for(ll i=1,l=0,r=0;ir){ // we are outside the segment [ l - r ] + l=r=i; // we have to start traversing from here and compare the elements to corresponding starting element till we get any mismatch or end of the text/array + while(r zarr = zfunction(s); // calling Z-function + + // printing z array + + for(ll i=0;i