Regex Pattern Matcher - Problem

Build a simple regex engine that supports . (matches any character), * (matches zero or more of the preceding character), and ? (matches zero or one of the preceding character) wildcards for pattern matching.

Pattern Rules:

  • . matches any single character
  • * matches zero or more occurrences of the character immediately before it
  • ? matches zero or one occurrence of the character immediately before it
  • Regular characters match themselves exactly

Return true if the entire string matches the pattern, false otherwise.

Input & Output

Example 1 — Basic Wildcard Matching
$ Input: text = "ab", pattern = "a*b"
Output: true
💡 Note: Pattern 'a*' matches 'a' (one occurrence of 'a'), then 'b' matches 'b' exactly
Example 2 — Dot Wildcard
$ Input: text = "ac", pattern = "a."
Output: true
💡 Note: '.' matches any character, so 'a.' matches 'ac' where '.' matches 'c'
Example 3 — Question Mark Optional
$ Input: text = "ab", pattern = "ab?"
Output: true
💡 Note: 'b?' means 'b' is optional, but 'b' is present, so pattern matches

Constraints

  • 1 ≤ text.length ≤ 1000
  • 1 ≤ pattern.length ≤ 1000
  • text contains only lowercase English letters
  • pattern contains lowercase English letters, '.', '*', and '?'

Visualization

Tap to expand
INPUTALGORITHMRESULTabText: "ab"a*bPattern: "a*b"• . matches any character• * matches 0+ of previous• ? matches 0 or 1 of previous1Build DP Table2Handle base cases:dp[0][0] = true3Fill table using:For *: try 0 or more matchesFor .: match any character4Return dp[m][n]TRUEPattern Matches!"a*b" successfullymatches text "ab"• a* matches "a"• b matches "b"Key Insight:Dynamic programming builds a table systematically, avoiding exponential recursion bysolving each subproblem exactly once and reusing results.TutorialsPoint - Regex Pattern Matcher | Dynamic Programming
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
98.5K Views
Medium Frequency
~35 min Avg. Time
2.8K 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