Tutorialspoint
Problem
Solution
Submissions

Wildcard Matching

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to implement wildcard pattern matching with support for '?' and '*'. The '?' matches any single character and '*' matches any sequence of characters (including empty sequence). The matching should cover the entire input string (not partial).

Example 1
  • Input: s = "adceb", p = "*a*b*"
  • Output: true
  • Explanation:
    • The pattern "*a*b*" can match "adceb".
    • First '*' matches "", 'a' matches 'a', second '*' matches "dce", 'b' matches 'b', third '*' matches "".
    • Therefore, the string matches the pattern.
Example 2
  • Input: s = "acdcb", p = "a*c?b"
  • Output: false
  • Explanation:
    • The pattern "a*c?b" cannot match "acdcb".
    • 'a' matches 'a', '*' matches "d", 'c' matches 'c', '?' should match 'd' but we need 'b' at the end.
    • Since the pattern doesn't fully match, return false.
Constraints
  • 0 <= s.length, p.length <= 2000
  • s contains only lowercase English letters
  • p contains only lowercase English letters, '?' or '*'
  • Time Complexity: O(m*n) where m and n are lengths of string and pattern
  • Space Complexity: O(m*n)
StringsDynamic Programming CapgeminiSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem efficiently
  • Create a 2D DP table where dp[i][j] represents if first i characters of string match first j characters of pattern
  • Handle base cases: empty string with empty pattern, empty string with pattern containing only '*'
  • For '*', consider two cases: match empty sequence or match one or more characters
  • For '?', it matches exactly one character
  • For regular characters, they must match exactly

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents if first i characters of string match first j characters of pattern
 Step 2: Initialize base cases - empty string matches empty pattern, and handle patterns starting with '*'
 Step 3: For each cell, if pattern character is '*', it can match empty sequence (dp[i][j-1]) or one/more characters (dp[i-1][j])
 Step 4: If pattern character is '?' or matches string character, check diagonal cell dp[i-1][j-1]
 Step 5: Fill the entire DP table using the above logic
 Step 6: Return dp[m][n] which represents if entire string matches entire pattern
 Step 7: The time complexity is O(m*n) and space complexity is O(m*n)

Submitted Code :