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

static const int POW = 29;
class Solution {
public:
    vector<unsigned long long> powers;
    string longestDupSubstring(string s) {
        string answer;

        unsigned long long tmp = 1;
        powers.push_back(tmp);
        for(int i = 1; i < s.size(); ++i) {
            tmp *= POW;
            powers.push_back(tmp);
        }

        int low = 0, high = s.size();
        while(low < high) {
            int len = (low + high ) / 2;
            string res = duplicate(s, len);

            if(res.length() > 0) {
                if(res.length() > answer.length())
                    answer = res;
                low = len + 1;
            }
            else
                high = len;
        }
        return answer;
    }
    string duplicate(string &s, int len) {
        if(len == 0)
            return "";
        unordered_map<unsigned long long, int> seen;
        unsigned long long val = 0;
        for(int i = 0;i < len;++i){
            val = val*POW + s[i]-'a';
        }
        seen[val] = true;


        for(int i = len; i < s.size(); ++i) {
            val -= powers[len-1] * (unsigned long long)(s[i - len] - 'a');
            val *= POW;
            val += s[i] - 'a';

            if(seen.find(val) != seen.end()) {
                return s.substr(i - len + 1, len);
            }
            seen[val] = i;
        }
        return "";
    }
};
267620