Wildcard Matching - Problem

Given an input string s and a pattern p, implement wildcard pattern matching with support for '?' and '*':

  • '?' matches any single character
  • '*' matches any sequence of characters (including the empty sequence)

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

Input & Output

Example 1 — Basic Wildcard Matching
$ Input: s = "adceb", p = "*a*b*"
Output: true
💡 Note: The first '*' matches "ad", 'a' matches 'a', the second '*' matches "ce", 'b' matches 'b', and the last '*' matches the empty string.
Example 2 — No Match
$ Input: s = "adceb", p = "*a*b"
Output: false
💡 Note: Pattern ends with 'b' but string ends with 'b'. However, the pattern requires exact match of entire string, and there are extra characters after matching.
Example 3 — Question Mark Wildcard
$ Input: s = "cb", p = "?a"
Output: false
💡 Note: '?' matches 'c', but 'a' doesn't match 'b', so the pattern fails.

Constraints

  • 0 ≤ s.length, p.length ≤ 2000
  • s contains only lowercase English letters
  • p contains only lowercase English letters, '?' or '*'

Visualization

Tap to expand
INPUTString s = "adceb"adcebPattern p = "*a*b*"*a*b*Wildcards:? = any single char* = any sequenceALGORITHM1Create DP Table2Fill Base Cases3Use Recurrence:if p[j] == '*': dp[i][j] = dp[i-1][j] || dp[i][j-1]elif p[j] == '?' or p[j] == s[i]: dp[i][j] = dp[i-1][j-1]4Return dp[n][m]Time: O(n × m)Space: O(n × m)RESULTFinal Answer:trueMatch Breakdown:* matches ""a matches "a"* matches "dc"b matches "e"... wait!Actually: "adceb" vs "*a*b*"Correct match possibleKey Insight:Wildcard '*' creates multiple matching possibilities - use DP to explore all valid pathssystematically. Each cell dp[i][j] represents whether prefix s[0:i] matches prefix p[0:j].TutorialsPoint - Wildcard Pattern Matching | Dynamic Programming
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
125.0K Views
Medium Frequency
~35 min Avg. Time
3.3K 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