Solving Leetcode Interviews in Seconds with AI: Wildcard Matching
Introduction
In this blog post, we will explore how to solve the LeetCode problem "44" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '' where: '?' Matches any single character. '' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Example 1: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "" Output: true Explanation: '' matches any sequence. Example 3: Input: s = "cb", p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Constraints: 0 <= s.length, p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters, '?' or '*'.
Explanation
Here's a breakdown of the approach, complexity, and the Python code:
High-Level Approach:
- Dynamic Programming: Use a 2D boolean table
dpwheredp[i][j]indicates whether the firsticharacters of the stringsmatch the firstjcharacters of the patternp. - Base Cases: Initialize the first row and column of the
dptable.dp[0][0]is True (empty string matches empty pattern). Handle cases where the pattern starts with*(it can match the empty string). - Iteration: Iterate through the
dptable, filling it based on the current characters insandp. Ifp[j-1]is?, the result depends on the match of substringss[0:i-1]andp[0:j-1]. Ifp[j-1]is*, we consider two cases: either*matches an empty sequence or it matches one or more characters ins. Otherwise, compare current chars ofsandp.
- Dynamic Programming: Use a 2D boolean table
Complexity:
- Runtime: O(m*n) where n is the length of
sand m is the length ofp. - Space: O(m*n)
- Runtime: O(m*n) where n is the length of
Code
def isMatch(s: str, p: str) -> bool:
"""
Implements wildcard pattern matching with support for '?' and '*'.
"""
n = len(s)
m = len(p)
dp = [[False] * (m + 1) for _ in range(n + 1)]
# Empty string matches empty pattern
dp[0][0] = True
# Handle cases where the pattern starts with '*'
for j in range(1, m + 1):
if p[j - 1] == '*':
dp[0][j] = dp[0][j - 1]
# Iterate through the dp table
for i in range(1, n + 1):
for j in range(1, m + 1):
if p[j - 1] == '?':
dp[i][j] = dp[i - 1][j - 1]
elif p[j - 1] == '*':
dp[i][j] = dp[i][j - 1] or dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j - 1] and (s[i - 1] == p[j - 1])
return dp[n][m]