↓Skip to main content
  1. LeetCode/

LeetCode 187: Repeated DNA Sequences

·1 min· ·
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-14

  • Submissions: Accepted (first try)

Approach
#

Enumerate every length-10 substring (String Template 3, the fixed window of Sliding Window Template 1), count them in a hash map (Hash Table Template 1), and return those with count above 1.

My Attempts
#

Passed on the first try. The loop ran to len(s), adding tail fragments shorter than 10, but each appears once, so the answer was unaffected.

Solution
#

class Solution:
    def findRepeatedDnaSequences(self, s: str) -> List[str]:
        cnt = Counter(s[i:i + 10] for i in range(len(s) - 9))
        return [seq for seq, c in cnt.items() if c > 1]

Complexity
#

Time O(10n), space O(10n).

Mistakes to Avoid
#

  • Start indices go up to len(s) - 10; otherwise tail fragments shorter than 10 get counted.
  • Do not use s.count(seq): it counts non-overlapping occurrences and misses "AAAAAAAAAAA".

Interview Explanation
#

I count every length-10 substring in a hash map and return those seen more than once. Each substring has fixed length 10, so time and space are O(n); to optimize further, encode A, C, G, T in 2 bits each and use a rolling hash for O(1) per shift.

Related

LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k
LeetCode 208: Implement Trie (Prefix Tree)
·2 mins
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 note: each node is a children dict plus an is_end flag; insert, search and startsWith all walk down character by character
LeetCode 981: Time Based Key-Value Store
·2 mins
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 note: store a (timestamp, value) list per key, with timestamps increasing; get binary searches the last timestamp <= the query
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains