<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p>

<ul>
	<li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li>
</ul>

<p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p>

<p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
<strong>Output:</strong> ["AAAAACCCCC","CCCCCAAAAA"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "AAAAAAAAAAAAA"
<strong>Output:</strong> ["AAAAAAAAAA"]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
	<li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li>
</ul>

class Solution {
public:
    int hashVal(char c) {
        switch (c) {
            case 'A': return 0;
            case 'C': return 1;
            case 'G': return 2;
            case 'T': return 3;
            default: return 0;
        }
    }

    vector<string> findRepeatedDnaSequences(string s) {
        if (s.length() < 10) return {};

        unordered_map<int, vector<int>> hash_map;  // Stores the hash value and corresponding start indices
        unordered_set<string> result_set;
        vector<string> result;

        int hash = 0;
        int base = 4;
        int window = 10;
        int highestBase = pow(base, window - 1);  // base^9

        // Calculate the hash value for the first window
        for (int i = 0; i < window; i++) {
            hash = hash * base + hashVal(s[i]);
        }
        hash_map[hash].push_back(0);

        // Sliding window
        for (int i = window; i < s.length(); i++) {
            // Remove the leftmost character and add the new rightmost character to the hash
            hash = (hash - hashVal(s[i - window]) * highestBase) * base + hashVal(s[i]);
            
            // Check if this hash has been seen before
            if (hash_map.find(hash) != hash_map.end()) {
                result_set.insert(s.substr(i - window + 1, window));
            }
            // Add the current starting index to the hash_map
            hash_map[hash].push_back(i - window + 1);
        }

        for (const string& seq : result_set) {
            result.push_back(seq);
        }

        return result;
    }
};
26621