Substring Matching Pattern - Problem

Imagine you're building a search engine that needs to handle wildcard patterns. You have a text string s and a pattern p that contains exactly one * character acting as a wildcard.

The * character can be replaced with any sequence of zero or more characters (including an empty string). Your task is to determine if the pattern p can be made to match any substring of s.

Goal: Return true if pattern p can match a substring of s, false otherwise.

Example: If s = "hello world" and p = "wo*d", we can replace * with "rl" to get "world", which is a substring of s.

Input & Output

example_1.py โ€” Basic Match
$ Input: s = "hello world", p = "wo*d"
โ€บ Output: true
๐Ÿ’ก Note: We can replace * with "rl" to get "world", which is a substring of "hello world"
example_2.py โ€” Empty Replacement
$ Input: s = "programming", p = "pro*ing"
โ€บ Output: true
๐Ÿ’ก Note: We can replace * with "gramm" to get "programming", which matches the entire string
example_3.py โ€” No Match
$ Input: s = "hello", p = "wor*ld"
โ€บ Output: false
๐Ÿ’ก Note: Neither "wor" nor "ld" appear in "hello", so no valid substring can be formed

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • 1 โ‰ค p.length โ‰ค 103
  • s contains only lowercase English letters
  • p contains only lowercase English letters and exactly one '*' character
  • The '*' character cannot be at the start or end of p

Visualization

Tap to expand
Wildcard Pattern Matching VisualizationString: "hello world programming""wor"Prefix*Wildcard"ing"SuffixSearch ProcessStep 1Find "wor" atposition 6Step 2Check if "ing"appears afterStep 3Match found!"programming"โœ“ Pattern "wor*ing" matches substring "programming"
Understanding the Visualization
1
Split the Pattern
Divide pattern at * into prefix and suffix parts
2
Search for Prefix
Find all positions where the prefix appears in the string
3
Check Suffix Placement
For each prefix position, see if suffix can appear later
4
Validate Match
Ensure there's valid spacing between prefix and suffix
Key Takeaway
๐ŸŽฏ Key Insight: By splitting the pattern at the wildcard, we can efficiently search for the fixed parts and validate that they can be connected with any middle section.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
26.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen