LeetCode 187: Repeated DNA Sequences
Problem Description
Explanation
To solve this problem, we can use a sliding window of size 10 to iterate through the input DNA sequence. We will keep track of all the 10-letter-long substrings we have seen so far using a HashMap to store the substrings and their frequencies. If we encounter a substring that has already been seen, we add it to the result list.
- Create a HashMap to store the substrings and their frequencies.
- Iterate through the input DNA sequence using a sliding window of size 10.
- For each window, check if the substring is already in the HashMap.
- If the substring is not in the HashMap, add it with a frequency of 1.
- If the substring is already in the HashMap, increment its frequency and check if it has occurred more than once.
- Add the repeated substrings to the result list.
- Return the list of repeated substrings.
Time Complexity: O(n), where n is the length of the input DNA sequence. Space Complexity: O(n), where n is the number of unique 10-letter-long substrings in the input DNA sequence.
Solutions
import java.util.*;
class Solution {
public List<String> findRepeatedDnaSequences(String s) {
List<String> result = new ArrayList<>();
Map<String, Integer> substrings = new HashMap<>();
for (int i = 0; i <= s.length() - 10; i++) {
String sub = s.substring(i, i + 10);
substrings.put(sub, substrings.getOrDefault(sub, 0) + 1);
if (substrings.get(sub) == 2) {
result.add(sub);
}
}
return result;
}
}
Related LeetCode Problems
Loading editor...