CSES - Shared codeLink to this code:
https://cses.fi/paste/eb1576bc1900b84776a439/
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll p = 101, mod = 1e9+7;
string s;
int main(){
cin.tie(nullptr)->sync_with_stdio(0);
// freopen("in_all.txt", "r", stdin);
// freopen("out_all.txt", "w", stdout);
cin >> s;
int n=s.size(), l=1, r=n, idx=-1;
while(l<r){
int m = (l+r+1)>>1;
bool ok=false;
ll hs=0, fr=1;
map<ll, bool> mp;
for(int i=0;i<m;i++) hs=hs*p%mod+s[i]-'a', fr=fr*p%mod;
hs%=mod;
mp[hs]=1;
for(int i=m;i<n;i++){
hs=hs*p%mod+s[i]-'a';
hs-=fr*(s[i-m]-'a')%mod;
hs+=mod, hs%=mod;
if(mp.find(hs)!=mp.end()){
ok=true;
idx=i;
break;
}
mp[hs]=1;
}
if(ok) l=m;
else r=m-1;
}
if(idx==-1) cout << -1;
else for(int i=idx-l+1;i<=idx;i++) cout << s[i];
return 0;
}