Find All Pattern Positions in Text
StringsAuto-graded · 20 test casesLast updated
Tests implementation of efficient string matching and understanding of linear-time pattern search algorithms.
Write a function that locates every position where a given pattern appears within a text string.
Your function should accept two strings: a text to search within and a pattern to search for. Return a list containing the starting index of each occurrence of the pattern in the text. If the pattern appears multiple times with overlapping positions, include all of them.
Your implementation must be more efficient than checking every possible starting position independently.
Constraints
1 <= len(text) <= 10^61 <= len(pattern) <= 10^4- Both strings contain only ASCII characters
- If the pattern is longer than the text, return an empty list
- If the pattern is empty, return an empty list
- Indices are 0-based
Examples
Example 1
Input: find_all_matches('ababcababa', 'aba')
Output: [0, 5, 7]
Hints
Hint 1
Consider preprocessing the pattern to avoid redundant comparisons when a mismatch occurs
Hint 2
Track the longest prefix of the pattern that matches a suffix of what you've seen so far
Hint 3
The Knuth-Morris-Pratt algorithm achieves O(N + M) time by never backtracking in the text
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive solution would check every position in the text as a potential starting point, comparing the pattern character by character. This leads to O(N × M) time complexity where N is the text length and M is the pattern length.
The Knuth-Morris-Pratt (KMP) algorithm achieves O(N + M) by avoiding redundant comparisons. The key insight: when a mismatch occurs, we already know some characters in the text (those that matched), so we can skip ahead intelligently rather than restarting from scratch.
Step 1: Build the Prefix Table
First, preprocess the pattern to compute a prefix function for each position. This function tells us the length of the longest proper prefix of the pattern up to that position which is also a suffix of that substring. This captures the internal structure of repeated substrings within the pattern.
Build this table by matching the pattern against itself, using the same logic we'll use for the main search.
Step 2: Scan the Text
Maintain a pointer tracking how many consecutive pattern characters we've matched so far. For each text character:
- If it matches the next pattern character, advance the pattern pointer
- On a mismatch, use the prefix table to determine the longest partial match we can keep without backtracking in the text
- When the pattern pointer reaches the end, we've found a complete match—record its starting position
- After finding a match, use the prefix table to continue searching for overlapping matches
This ensures we never move backward in the text, giving us linear time complexity.
Correctness
The algorithm maintains the invariant that after processing each text position, the pattern pointer equals the length of the longest prefix of the pattern that ends at the current text position. When a mismatch occurs, any shorter valid match must be a border (both a prefix and suffix) of what we've matched so far. The prefix table gives us exactly this information, ensuring no potential matches are missed.
Complexity
- Time: O(N + M) where N is the text length and M is the pattern length. The pattern pointer increases by at most 1 per character and decreases only when using the prefix table. Since the total number of decreases is bounded by the total increases, the amortized work per character is constant.
- Space: O(M) for the prefix table, plus O(K) for the output where K is the number of matches.
Solution
from typing import List
def find_all_matches(text: str, pattern: str) -> List[int]:
if not pattern or len(pattern) > len(text):
return []
prefix = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[i] != pattern[j]:
j = prefix[j - 1]
if pattern[i] == pattern[j]:
j += 1
prefix[i] = j
occurrences = []
j = 0
for i, char in enumerate(text):
while j > 0 and char != pattern[j]:
j = prefix[j - 1]
if char == pattern[j]:
j += 1
if j == len(pattern):
occurrences.append(i - len(pattern) + 1)
j = prefix[j - 1]
return occurrences