KatInterview

Find All Pattern Positions in Text

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringsstring-matchingkmppattern-search

Last 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^6
  • 1 <= 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