#44

Wildcard Matching

Hard
StringDynamic ProgrammingGreedyRecursionDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m)Space O(n * m)

Using dynamic programming, we can build a table to store results of subproblems. This allows us to avoid redundant calculations and efficiently determine if the pattern matches the string.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a 2D DP table where dp[i][j] indicates if s[0..i-1] matches p[0..j-1].
  2. 2Step 2: Initialize dp[0][0] to true (empty string matches empty pattern).
  3. 3Step 3: Fill the first row for patterns that start with '*'.
  4. 4Step 4: Iterate through each character of the string and pattern, updating the DP table based on matches and '*' handling.
  5. 5Step 5: Return the value at dp[s.length()][p.length()] for the final result.
solution.py13 lines
1def isMatch(s, p):
2    dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
3    dp[0][0] = True
4    for j in range(1, len(p) + 1):
5        if p[j - 1] == '*':
6            dp[0][j] = dp[0][j - 1]
7    for i in range(1, len(s) + 1):
8        for j in range(1, len(p) + 1):
9            if p[j - 1] == s[i - 1] or p[j - 1] == '?':
10                dp[i][j] = dp[i - 1][j - 1]
11            elif p[j - 1] == '*':
12                dp[i][j] = dp[i][j - 1] or dp[i - 1][j]
13    return dp[len(s)][len(p)]

Complexity note: The time complexity is O(n * m) because we fill a table of size (n+1) x (m+1), where n is the length of the string and m is the length of the pattern.

  • 1Understanding how '*' and '?' work is crucial.
  • 2Dynamic programming can significantly reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.