C++ · Solution

String Overlap

This C++ solution uses prefix sums for String Overlap. Read the reasoning, inspect the code, or try your own test case below.

StringsPrefix sumsC++30 lines
Solution204of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Prefix sums

String Overlap: precompute cumulative information so each later interval or prefix can be evaluated from a small number of stored values.

Arrays

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

View exact source file ↗
Implementation

String_Overlap.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const long long INF = 1e17; //❄️
    int main() {
        ios::sync_with_stdio(0); cin.tie(0); 
        string s, ss; cin >> s >> ss;
        int ans = 0;
        // for (int i = 0; i < min(s.size(), ss.size()); i++) {
        //     if (s.substr(s.size() - i - 1, i + 1) == ss.substr(0, i + 1) || ss.substr(ss.size() - i - 1, i + 1) == s.substr(0, i + 1)) ans = max(ans, i + 1);
        // }
        auto prefix_function = [&] (string a) {
            vector<int> pi(a.size());
            for (int i = 1; i < a.size(); i++) {
                int j = pi[i-1];
                while (j > 0 && a[i] != a[j]) {
                    j = pi[j-1];
                }
                if (a[i] == a[j]) j++;
                pi[i] = j;
            }
            return pi;
        };
        vector<int> pi = prefix_function(s + "#" + ss);
        ans = max(ans, pi.back());
        pi = prefix_function(ss + "#" + s);
        ans = max(ans, pi.back());
        cout << ans << '\n';
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.