<p>Given a string <code>s</code>, consider all <em>duplicated substrings</em>: (contiguous) substrings of s that occur 2 or more times.&nbsp;The occurrences&nbsp;may overlap.</p>

<p>Return <strong>any</strong> duplicated&nbsp;substring that has the longest possible length.&nbsp;If <code>s</code> does not have a duplicated substring, the answer is <code>&quot;&quot;</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "banana"
<strong>Output:</strong> "ana"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "abcd"
<strong>Output:</strong> ""
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    string longestDupSubstring(string s) {
        s_ = s; // copy s

        // initialize prefix hash
        prefix_hash_ = vector<unsigned long long>(s.size());
        prefix_hash_[0] = s[0] - 'a' + 1;
        for (int i = 1; i < s.size(); i++) {
            prefix_hash_[i] = prefix_hash_[i - 1] * kBase + (s[i] - 'a' + 1);
        }
        // initialize kBase^n vector
        powers_ = vector<unsigned long long>(s.size());
        powers_[0] = 1;
        for (int i = 1; i < s.size(); i++) {
            powers_[i] = powers_[i - 1] * kBase;
        }

        if (!test(1)) {
            return "";
        }

        // found largest length that test positive
        int l = 1, r = s.size() - 1;
        while (l < r) { 
            int mid = (l + r + 1) / 2;
            if (test(mid)) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        return s.substr(start_, l);

    }
private:
    unsigned long long hash(int index, int length) {
        if (index == 0) {
            return prefix_hash_[length - 1];
        }
        return prefix_hash_[index + length - 1] - prefix_hash_[index - 1] * powers_[length];
    }

    bool test(int length) {
        unordered_set<unsigned long long> found;
        for (int i = 0; i + length - 1 < s_.size(); i++) {
            unsigned long long k = hash(i, length);
            if (found.contains(k)) {
                start_ = i;
                return true;
            }
            found.insert(k);
        }
        return false;
    }

    string s_;
    vector<unsigned long long> prefix_hash_;
    vector<unsigned long long> powers_;
    static const unsigned long long kBase = 131;
    int start_;
};
221540