Official

B - Longest Uncommon Prefix Editorial by en_translator


In competitive programming, some problem statements may be a bit hard to understand at a glance. I personally think this problem is one of them.
In such case, refer to the description of the samples. That may make it easier to understand.


Since the constraint is as small as \(N \le 5000\), we can see that we may spend about \(O(N)\) time for each \(i\).
Therefore, the following naive loop solution is valid.

  • For each \(i=1,2,\dots,N-1\), do the following:
    • For each \(j=1,2,\dots\), do the following:
      • If \(i+j > N\), the answer to \(i\) is \(j-1\).
      • If \(S_j = S_{j+i}\), the answer to \(i\) is \(j-1\).
      • Otherwise, continue the \(j\) loop.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int n;
  string s;
  cin >> n >> s;
  for(int i=1;i<n;i++){
    for(int j=1;j<=n;j++){
      if(i+j>n){cout << j-1 << "\n";break;}
      if(s[j-1]==s[j+i-1]){cout << j-1 << "\n";break;}
    }
  }
  return 0;
}

posted:
last update: