Given a DNA string text over the alphabet {A, C, G, T} and a list of query strings patterns over the same alphabet, find every occurrence of any pattern as a substring of text. Overlapping occurrences must all be reported.
Each occurrence is a pair [pattern_index, start_index], where pattern_index is the position of the matched pattern in patterns and start_index is the 0-indexed position in text where the match begins.
Return all occurrences sorted by start_index ascending. When two occurrences share the same start_index, order them by pattern_index ascending.
Function Signature
def find_occurrences(text: str, patterns: list[str]) -> list[list[int]]:
Rules
-
Each occurrence is a two-element list
[pattern_index, start_index]
.
-
Overlapping matches all count. A match of one pattern inside a match of another (such as
"A"
inside
"AA"
) is reported too.
-
patterns
may contain the same string more than once. Each index is its own pattern and gets its own entries.
-
If nothing matches, return an empty list.
Constraints
-
1 <= len(text) <= 10^5
-
1 <= len(patterns) <= 10^4
-
1 <= len(patterns[i]) <= 100
-
text
and every
patterns[i]
contain only
'A'
,
'C'
,
'G'
and
'T'
.
Examples
Input: text = "ACACAGT", patterns = ["ACA", "CAG", "GT"]
Output: [[0, 0], [0, 2], [1, 3], [2, 5]]
"ACA" occurs at indices 0 and 2 (the two matches share the A at index 2), "CAG" occurs at index 3, and "GT" occurs at index 5. Sorting by start index gives the order shown.
Input: text = "AAAA", patterns = ["A", "AA"]
Output: [[0, 0], [1, 0], [0, 1], [1, 1], [0, 2], [1, 2], [0, 3]]
"A" matches at 0, 1, 2 and 3, and "AA" matches at 0, 1 and 2. At each shared start index the pair for pattern 0 comes before the pair for pattern 1.
Input: text = "GATTACA", patterns = ["TA", "A", "TA"]
Output: [[1, 1], [0, 3], [2, 3], [1, 4], [1, 6]]
"A" matches at 1, 4 and 6. "TA" matches once, at index 3, and since it appears twice in patterns, both index 0 and index 2 are reported at start 3.