Repeated DNA Sequences
The DNA sequence is composed of a series of nucleotides abbreviated as 'A''C''G''T'
-
For example,
is a DNA sequence."ACGAATTCCG"
When studying DNA, it is useful to identify repeated sequences within the DNA.
Given a string s10
Example 1
Output: ["AAAAACCCCC","CCCCCAAAAA"]
Example 2
Output: ["AAAAAAAAAA"]
Constraints:
1 <= s.length <= 105 is eithers[i] ,'A' ,'C' , or'G' .'T'
Solution 1 - Generate all possible substrings of length 10 and track repeated substrings
In this approach, we will be generating all possible substrings with length 10 and keep track of their count in a HashMapsubstringcountresult
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class RepeatedDNASequences {
static List<String> findRepeatedDnaSequences(String s) {
List<String> result = new ArrayList<>();
HashMap<String, Integer> seen = new HashMap<>();
int i =0;
while(i <s.length()-9) {
String substring = s.substring(i, i+10);
int timesSeen = seen.merge(substring, 1, Integer::sum);
if(timesSeen == 2) {
result.add(substring);
}
i++;
}
return result;
}
public static void main(String[] args) {
System.out.println(findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where ns
Space complexity: O(n)
Above implementations source code can be found at