<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
{
    string text;
    string HashRolling(int k)
    {
        unordered_map<int, vector<int>> mymap;
        int hash1 = 0;
        int p = 5003;
        int d1 = 1, d2 = 1;

        for (int i = k - 1; i >= 0; i--)
        {
            hash1 = (hash1 + ((text[i] - 'a' + 1) * d1) % p) % p;
            d2 = d1;
            d1 = (d1 * 26) % p;
        }
        mymap.insert({hash1, {0}});
        for (int i = k, j = 0; i < text.length(); i++, j++)
        {
            hash1 = (hash1 - ((text[j] - 'a' + 1) * d2) % p + p) % p;
            hash1 = (hash1 * 26) % p;
            hash1 = (hash1 + (text[i] - 'a' + 1)) % p;
            if (mymap.find(hash1) != mymap.end())
            {
                vector<int> l1 = mymap[hash1];

                for (int i4 = 0; i4 < l1.size(); i4++)
                {
                    int i1 = l1[i4];
                    bool b1 = true;
                    for (int t1 = i1, j1 = j + 1; t1 < i1 + k; j1++, t1++)
                    {
                        if (text[t1] != text[j1])
                        {
                            b1 = false;
                            break;
                        }
                    }
                    if (b1 == true)
                    {
                        return text.substr(j + 1, k);
                    }
                }
            }
            mymap[hash1].push_back(j + 1);
        }

        return "";
    }

    string helper(int s, int e)
    {
        string ans = "";
        while (s <= e)
        {
            int mid = (s + e) / 2;
            string temp = HashRolling(mid);
            if (temp == "")
            {
                e = mid - 1;
            }
            else
            {
                s = mid + 1;
                ans = temp;
            }
        }
        return ans;
    }

public:
    string longestDupSubstring(string s)
    {
        this->text = s;
        return helper(0, s.length());
    }
};
290660