<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>the maximum length of a subarray that appears in <strong>both</strong> arrays</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The repeated subarray with maximum length is [3,2,1].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The repeated subarray with maximum length is [0,0,0,0,0].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 100</code></li>
</ul>

#define ll long long

class Solution {
    ll mod=1e9+7;
    ll p=131;
    ll power(ll a, ll b)
    {
        a%=mod;
        ll res=1;
        while(b>0)
        {
            if(b&1)
            {
                res=(res*a)%mod;
            }
            a=(a*a)%mod;
            b/=2;
        }
        return res;
    }
    ll inv(ll n)
    {
        return power(n, mod-2);
    }
    ll poly_hash(vector<int>& v, int s, int e)
    {
        ll hash = 0;
        ll p_power = 1;
        for (int i = s; i <= e; i++)
        {
            hash += (v[i]+1)*p_power;
            p_power *= p;

            hash %= mod;
            p_power %= mod;
        }
        return hash;
    }
    bool pos(vector<int>& nums1, vector<int>& nums2, int mid)
    {
        ll h1=poly_hash(nums1, 0, mid-1);
        int n=nums1.size(), m=nums2.size();
        map<int, int> m1;
        m1[h1]++;
        for (int i = 1; i+mid <= n; i++)
        {
            h1=(h1-(nums1[i-1]+1)+mod)%mod;
            h1=(h1*inv(p))%mod;
            h1=(h1+(nums1[i+mid-1]+1)*power(p, mid-1))%mod;
            m1[h1]++;
        }
        ll h2=poly_hash(nums2, 0, mid-1);
        if(m1.count(h2)) return true;
        for (int i = 1; i+mid <= m; i++)
        {
            h2=(h2-(nums2[i-1]+1)+mod)%mod;
            h2=(h2*inv(p))%mod;
            h2=(h2+(nums2[i+mid-1]+1)*power(p, mid-1))%mod;
            if(m1.count(h2)) return true;
        }
        return false;
    }

public:
    int findLength(vector<int>& nums1, vector<int>& nums2) {
        int ans=0;
        int si=1;
        int ei=min(nums1.size(), nums2.size());
        while(si<=ei)
        {
            int mid=si+(ei-si)/2;
            if(pos(nums1, nums2, mid))
            {
                si=mid+1;
                ans=mid;
            }
            else
            {
                ei=mid-1;
            }
        }
        return ans;
    }
};
19318