LeetCode 187: Repeated DNA Sequences Solution

Master LeetCode problem 187 (Repeated DNA Sequences), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

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.

  1. Create a HashMap to store the substrings and their frequencies.
  2. Iterate through the input DNA sequence using a sliding window of size 10.
  3. For each window, check if the substring is already in the HashMap.
  4. If the substring is not in the HashMap, add it with a frequency of 1.
  5. If the substring is already in the HashMap, increment its frequency and check if it has occurred more than once.
  6. Add the repeated substrings to the result list.
  7. 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.

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 187 (Repeated DNA Sequences)?

This page provides optimized solutions for LeetCode problem 187 (Repeated DNA Sequences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 187 (Repeated DNA Sequences)?

The time complexity for LeetCode 187 (Repeated DNA Sequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 187 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 187 in Java, C++, or Python.

Back to LeetCode Solutions