Problem 376272 · medium · Phase 03 Linear Management & Searching

First Match With Single-Character Wildcards

two pointers · strings · pattern matching

Given a string text and a pattern in which ? matches any single character, return the smallest index i such that pattern matches text[i:i+len(pattern)], or -1 if there is no match. An empty pattern matches at index 0.

Examples

Input:  text = "hello world", pattern = "l?o"
Output: 2
Explanation: "llo" starts at index 2.

Input:  text = "abcabc", pattern = "c?a"
Output: -1
Explanation: "c" appears at index 2 and 5, but neither is followed by any character and then "a".

Constraints

  • 0 <= len(text) <= 10**5, 0 <= len(pattern) <= 20
  • Target: O(len(text) * len(pattern)) time, O(1) extra space; do not use re or str.find.

Goals

  • Align a pattern at each candidate start and scan with a second pointer
  • Skip to the next start as soon as a mismatch appears
Starting Python…