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

#define ull unsigned long long

class Solution {
public:
    inline int hash(char ch) {
        return  1 << (ch - 'a');
    }
    int dubsubstr(string_view s, int m) {
        if (m == 0) return 0;
        ull hs = 0;
        short bits_per_char = 1 + (((8 * sizeof(hs)) - 1) / m);
        bits_per_char = min(bits_per_char, (short)8);
        ull charmask = (1LLU << (bits_per_char)) - 1;
        ull hashmask = (bits_per_char * m < 64) ? ((1LLU << (bits_per_char * m)) - 1) : ULLONG_MAX;
        // printf("bits_per_char = %d\ncharmask = %064llb\nhashmask = %064llb\n", bits_per_char, charmask, hashmask);
        int n = s.size(), i = 0;
        for (; i < m; i++) {
            hs <<= bits_per_char;
            hs |= ((ull)s[i] & charmask);
            hs &= hashmask;
        }
        unordered_map<ull, int> ma;
        ma[hs] = m;
        for (; i < n; i++) {
            hs <<= bits_per_char;
            hs |= ((ull)s[i] & charmask);
            hs &= hashmask;
            if (auto it = ma.find(hs); it != ma.end()) {
                if (char_traits<char>::compare(s.data() + i - m + 1, s.data() + it->second - m, m) == 0) {
                    return it->second - m;
                }
                // else {
                    
                //     cout << "collision: " << quoted(s.substr(i-m+1, m)) << " != " << quoted(s.substr(it->second - m, m)) << endl;
                //     printf("hash = %064llb\n", hs);
                // }
            }
            ma[hs] = i + 1;
        }
        return -1;
    }
    string longestDupSubstring(string s) {
        int n = s.size(), hi = n, lo = 0;
        while (hi > lo) {
            int m = lo + (hi - lo) / 2;
            if (dubsubstr(s, m) == -1) hi = m;
            else lo = m + 1;
        }
        hi--;
        int hashresult = dubsubstr(s, hi);
        return s.substr(hashresult, hi);
    }
};
238820