Repeated DNA Sequences (LeetCode 187): Solution and Explanation
Given a DNA string made of the letters A, C, G and T, return every 10-letter substring that appears more than once. Each repeated substring is listed once, in any order.
Intuition
There are only n - 9 windows of length 10, and a window repeats exactly when you meet it a second time. So walk the windows left to right and keep a set of the ones you have met. A second set of reported windows makes sure a sequence that appears three or more times is listed only once.
Putting 10-letter strings into a set works, but every window costs a 10-character slice and a string hash. The alphabet has just four letters, so each base fits in 2 bits and a whole window fits in a 20-bit integer.
That integer can be rolled: shift it left by 2 bits to make room, OR in the new base, and mask to 20 bits so the oldest base falls off the top. Each step is constant work, and equal windows always produce equal integers, so the set can hold numbers instead of strings.
Approach: 2-bit rolling code with two sets
- Map A, C, G, T to 0, 1, 2, 3 and set
mask = 2^20 - 1. - For each index
i, updateh = ((h << 2) | code[s[i]]) & mask. - While
i < 9the register is not full yet, so skip the check. - From
i = 9on,hencodess[i-9..i]. Ifhis inseenand not inadded, add it toaddedand append the substring to the answer. - Add
htoseenand continue.
Step-by-step example
s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
- Indices 0 to 8 fill the register with AAAAACCCC. No check yet.
- i = 9: the window AAAAACCCCC gets code 341 and goes into seen. Windows at i = 10 to 18 are all new as well.
- i = 19: the window is AAAAACCCCC again, code 341 is already in seen and not reported, so it is added to the answer.
- i = 20: the window AAAACCCCCC has six C's and is new, so it only goes into seen.
- i = 25: CCCCCAAAAA (code 349184, first met at i = 14) comes back and is reported. Nothing else repeats, so the answer is ["AAAAACCCCC","CCCCCAAAAA"].
Code: Python, Java, C++
1class Solution:
2 def findRepeatedDnaSequences(self, s: str) -> List[str]:
3 code = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
4 mask = (1 << 20) - 1
5 h, seen, added, res = 0, set(), set(), []
6 for i, ch in enumerate(s):
7 h = ((h << 2) | code[ch]) & mask
8 if i < 9:
9 continue
10 if h in seen and h not in added:
11 added.add(h)
12 res.append(s[i - 9:i + 1])
13 seen.add(h)
14 return res1class Solution {
2 public List<String> findRepeatedDnaSequences(String s) {
3 int[] code = new int[128];
4 code['C'] = 1; code['G'] = 2; code['T'] = 3;
5 int mask = (1 << 20) - 1, h = 0;
6 Set<Integer> seen = new HashSet<>(), added = new HashSet<>();
7 List<String> res = new ArrayList<>();
8 for (int i = 0; i < s.length(); i++) {
9 h = ((h << 2) | code[s.charAt(i)]) & mask;
10 if (i < 9) {
11 continue;
12 }
13 if (seen.contains(h) && added.add(h)) {
14 res.add(s.substring(i - 9, i + 1));
15 }
16 seen.add(h);
17 }
18 return res;
19 }
20}1class Solution {
2public:
3 vector<string> findRepeatedDnaSequences(string s) {
4 int code[128] = {0};
5 code['C'] = 1; code['G'] = 2; code['T'] = 3;
6 int mask = (1 << 20) - 1, h = 0;
7 unordered_set<int> seen, added;
8 vector<string> res;
9 for (int i = 0; i < (int)s.size(); i++) {
10 h = ((h << 2) | code[(unsigned char)s[i]]) & mask;
11 if (i < 9) {
12 continue;
13 }
14 if (seen.count(h) && added.insert(h).second) {
15 res.push_back(s.substr(i - 9, 10));
16 }
17 seen.insert(h);
18 }
19 return res;
20 }
21};Time and space complexity
O(n)
Each index does one shift, one OR, one mask and a few set operations on integers.
O(n)
The seen set can hold up to n - 9 codes. It is also capped at 2^20 entries because codes are 20-bit numbers.
Other approaches
Set of substrings (time O(10 * n), space O(10 * n))
Store every 10-letter slice in a hash set and report the ones met twice. It is the most readable version and passes easily, but each step builds and hashes a 10-character string.
Rabin-Karp polynomial hash (time O(n), space O(n))
Use a base-4 polynomial rolling hash. It is the general version of the same idea for larger alphabets or longer windows, where the code no longer fits in a machine word and collisions must be checked.
Common mistakes
- Reporting a sequence once per extra occurrence. Use a second set, or a count, so each one appears once in the answer.
- Checking windows before the register holds 10 letters, which compares partial codes.
- Forgetting the mask, so h keeps growing and two equal windows get different codes.
- Returning nothing special for strings shorter than 10. The loop simply never reaches a full window and the answer is empty, which is correct.
Frequently asked questions
Why does the 2-bit code never collide?
Each base gets a distinct 2-bit value and the 10 bases occupy fixed, separate bit positions, so the 20-bit number is a one-to-one encoding of the window. It is an exact code, not a hash.
Why is the answer in any order?
The problem only asks which sequences repeat. This solution reports them in the order their second occurrence is found.
What is the time complexity of Repeated DNA Sequences?
O(n) with the rolling 2-bit code, because each window is produced from the previous one in constant time. The plain substring set is O(10 * n), which is also linear for this fixed window size.