<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>

class Solution {
public:
  int findLength(vector<int>& nums1, vector<int>& nums2) {
    
    int m = nums1.size(), n = nums2.size(), ans = 0;
    string s;
    s.reserve(m+n+1);

    for( int i = 0 ; i < m ; ++i )
    s.push_back( (char)nums1[i] );

    s.push_back('x'); // char code > 100

    for( int i = 0 ; i < n ; ++i )
    s.push_back( (char)nums2[i] );

    auto x = sa(s), y = lcpa(s, x);

    for( int i = 0 ; i < m+n ; ++i )
    if( x[i] > m && x[i+1] < m || x[i] < m && x[i+1] > m )
    ans = max( ans, y[i] );

    return ans;
  }

private:
  
  // https://github.com/spaghetti-source/algorithm/
  vector<int> sa(const string &s) {

    #define all(c) ((c).begin()), ((c).end())
    
    int n = s.size();
    vector<int> x(n);

    vector<int> r(n), t(n); 
    for (int i = 0; i < n; ++i) r[x[i] = i] = s[i];
    for (int h = 1; t[n-1] != n-1; h *= 2) {
      auto cmp = [&](int i, int j) {
        if (r[i] != r[j]) return r[i] < r[j];
        return i+h < n && j+h < n ? r[i+h] < r[j+h] : i > j;
      };
      sort(all(x), cmp);
      for (int i = 0; i+1 < n; ++i) t[i+1] = t[i] + cmp(x[i], x[i+1]);
      for (int i = 0; i < n; ++i)   r[x[i]] = t[i];
    }

    return x;
  }

  // https://codeforces.com/blog/entry/12796
  vector<int> lcpa(const string &s, const vector<int> &sa) {
    
    int n=s.size(),k=0;
    vector<int> lcp(n,0);
    vector<int> rank(n,0);

    for(int i=0; i<n; i++) rank[sa[i]]=i;

    for(int i=0; i<n; i++, k?k--:0) {

      if(rank[i]==n-1) {k=0; continue;}
      int j=sa[rank[i]+1];
      while(i+k<n && j+k<n && s[i+k]==s[j+k]) k++;
      lcp[rank[i]]=k;
    }
    return lcp;
  }
};
15553