Problem 235298 · medium · Phase 02 Linear Data Structures

Find with Single-Character Wildcards

strings · pattern matching · iteration

Write find_pattern(text, pattern) that returns the list of all starting indices (in increasing order) at which pattern occurs in text. In the pattern, ? matches any single character; every other character must match exactly. A ? in the text is an ordinary character. Matches may overlap. Do not use the re module.

Examples

Input:  text = "abcabd", pattern = "ab?"
Output: [0, 3]

Input:  text = "aaaa", pattern = "a?"
Output: [0, 1, 2]

Input:  text = "xyz", pattern = "q"
Output: []

Constraints

  • 0 <= len(text) <= 10**4, 1 <= len(pattern) <= 20, printable ASCII
  • Target: O(len(text) * len(pattern)) time

Goals

  • Compare a pattern against every alignment of the text
  • Treat a wildcard as matching any character
  • Collect all overlapping match positions
Starting Python…