Regular Expression Matching - Problem

Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:

  • '.' matches any single character
  • '*' matches zero or more of the preceding element

The matching should cover the entire input string (not partial).

Input & Output

Example 1 — Basic Star Pattern
$ Input: s = "aa", p = "a*"
Output: true
💡 Note: The pattern 'a*' means zero or more 'a' characters. Since the string contains exactly two 'a's, the pattern matches.
Example 2 — Dot Wildcard
$ Input: s = "ab", p = ".*"
Output: true
💡 Note: The pattern '.*' means zero or more of any character. This can match any string, including 'ab'.
Example 3 — No Match
$ Input: s = "mississippi", p = "mis*is*p*."
Output: false
💡 Note: The pattern expects one more character at the end (the '.'), but the string ends after 'i'.

Constraints

  • 1 ≤ s.length ≤ 20
  • 1 ≤ p.length ≤ 30
  • s contains only lowercase English letters
  • p contains only lowercase English letters, '.', and '*'
  • '*' always appears after a preceding element

Visualization

Tap to expand
Regular Expression Matching INPUT String s: a a i=0 i=1 Pattern p: a * j=0 j=1 Operators: . any char * 0+ prev s = "aa" p = "a*" ALGORITHM STEPS 1 Create DP Table dp[i][j] = match s[0..i] with p[0..j] 2 Base Case dp[0][0] = true Handle x* patterns 3 Fill DP Table If char match or '.': dp[i][j]=dp[i-1][j-1] 4 Handle '*' 0 occur: dp[i][j-2] 1+ occur: dp[i-1][j] DP Table: a * "" T F T a F T T a F F T FINAL RESULT Pattern "a*" matches "aa" "aa" "a*" 'a*' = zero or more 'a' "aa" has two 'a' chars Output: true Full string matched! dp[2][2] = true Key Insight: Dynamic Programming builds solution bottom-up. For '*', we have two choices: 1) Use zero occurrences (skip x*) --> check dp[i][j-2] 2) Use one or more occurrences (if chars match) --> check dp[i-1][j]. Time: O(m*n), Space: O(m*n) TutorialsPoint - Regular Expression Matching | Optimal DP Solution
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
280.5K Views
High Frequency
~35 min Avg. Time
8.5K 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