The user wants a program that implements wildcard pattern matching.
This typically means implementing a function similar to Unix globbing, where ? matches a single character and * matches any sequence of characters (including empty).
1. Requirements & Constraints:
- Input: A text string (
s or text) and a pattern string (p or pattern).
- Output: Boolean (True/False) indicating if the pattern matches the text.
- Wildcards:
? matches exactly one character.
* matches zero or more of any character.
- Edge cases:
- Empty string, empty pattern.
- Pattern with multiple
* in a row.
- Very long strings (efficiency matters, usually O(N⋅M) or better).
2. Approaches:
-
Approach A: Recursion (Brute Force)
- Base cases: If pattern is empty, text must be empty.
- If chars match or pattern char is
?, recurse (text+1, pattern+1).
- If pattern char is
*:
- Option 1:
* matches nothing -> recurse (text, pattern+1).
- Option 2:
* matches current char -> recurse (text+1, pattern).
- Complexity: Exponential in worst case (lots of
*s). Too slow for large inputs.
-
Approach B: Dynamic Programming (DP)
dp[i][j] = true if text[0...i] matches pattern[0...j].
- Initialization:
dp[0][0] = true. dp[i][0] = false (non-empty text, empty pattern). dp[0][j] = dp[0][j-1] if pattern[j-1] == '*'.
- Transitions:
- If
pattern[j] == text[i] or pattern[j] == '?': dp[i][j] = dp[i-1][j-1].
- If
pattern[j] == '*': dp[i][j] = dp[i][j-1] (match empty) or dp[i-1][j] (match one or more).
- Complexity: Time O(N⋅M), Space O(N⋅M). (Can be optimized to space).
-
Approach C: Two Pointers (Greedy)
- Maintain pointers
i (text) and j (pattern).
- Also maintain
star_idx (last seen * in pattern) and match_idx (position in text when that * was encountered).
- Logic:
- If chars match or
?: i++, j++.
- If pattern is
*: Record star_idx = j, match_idx = i, move j++.
- If mismatch:
- If we have seen a
* previously (star_idx != -1): Backtrack. Reset j = star_idx + 1, match_idx++, i = match_idx. (Basically, use the previous * to consume one more character of text).
- Else: Return False.
- Complexity: Time O(N⋅M) (in worst case with lots of backtracking), but often linear O(N). Space .
3. Selecting the Best Approach for the User:
The user asked for a "program". Usually, they want something readable but efficient enough. The Two Pointers approach is the standard "optimal" interview solution, while DP is the standard "robust" academic solution. I will provide the Two Pointers approach because it's O(1) space and generally preferred in systems programming contexts. However, for clarity, I might briefly mention DP or provide the Two Pointer approach with good comments.
Actually, providing the DP solution is often safer because the logic is explicit and easier to debug for a beginner. But the Greedy approach is more impressive. I will implement the Greedy (Two Pointers) approach as the primary solution because it handles standard inputs best and is the "leet code" standard for this specific problem (LeetCode 44).
4. Drafting the Code (Python):
- Structure:
def is_match(text, pattern):
i, j = 0, 0
star_idx, match_idx = -1, 0
while i < len(text):
# Case 1: Match or '?'
if j < len(pattern) and (pattern[j] == text[i] or pattern[j] == '?'):
i += 1
j += 1
# Case 2: '*'
elif j < len(pattern) and pattern[j] == '*':
star_idx = j
match_idx = i
j += 1 # move pattern pointer, try to match 0 chars
# Case 3: Mismatch but we have a previous '*'
elif star_idx != -1:
j = star_idx + 1
match_idx += 1 # make '*' swallow one more char
i = match_idx
# Case 4: Mismatch and no star
else:
return False
# Check for remaining chars in pattern
while j < len(pattern) and pattern[j] == '*':
j += 1
return j == len(pattern)
5. Drafting the Code (C++):
Since the user didn't specify a language, I should probably provide Python and C++ or Java. Python is usually the go-to for pseudocode-like readability, C++ for performance. I'll stick to Python as the primary and maybe add C++ if requested, or just provide Python for simplicity. Let's stick to Python for clarity, but maybe include a C++ version for completeness if I feel generous. No, keep it simple: Python is the best default. Actually, I will provide both Python and C++ as they cover most bases.
6. Refinement and Testing (Mental Trace):
- Test 1:
text="aa", pattern="a" -> mismatch at end. i finishes, j not finished. Returns False. Correct.
- Test 2:
text="aa", pattern="*" -> star_idx=0. i advances. Loop ends. While loop skips *. j==len. Returns True. Correct.
- Test 3:
text="cb", pattern="?a" -> ? matches c. a vs b mismatch. No star. Returns False. Correct.
- Test 4:
text="adceb", pattern="*a*b" ->
* at 0. star=0, match=0.
a vs a. Match.
d vs *. star=2, match=2.
c vs b. Mismatch. star is 2. Backtrack. j=3, match=3, i=3.
- Wait, the backtracking logic needs to be precise.
- Let's re-trace
text="adceb", pattern="*a*b".
j=0: *. star=0, match=0, j=1.
j=1, i=0: a vs a. i=1, j=2.
j=2, i=1: *. star=2, match=1, j=3.
j=3, i=1: b vs d. Mismatch. star is 2. Backtrack. j=3, match=2, i=2. (Now * at index 2 matches 'd').
j=3, i=2: b vs c. Mismatch. star is 2. Backtrack. j=3, match=3, i=3. (* matches 'dc').
j=3, i=3: b vs e. Mismatch. star is 2. Backtrack. j=3, match=4, i=4.
j=3, i=4: b vs b. Match. i=5, j=4.
- End of text.
- End of pattern.
7. Final Polish:
I will present the solution in Python, as it's the most accessible. I will also include the Greedy (Two Pointers) approach because it is O(1) space and O(N⋅M) time, which is standard for this problem.
I will structure the response as:
- Explanation of the logic (Greedy approach).
- Python Implementation.
- C++ Implementation (optional but good for "program" requests).
- Example usage.
Let's just provide Python and C++. That covers 90% of users.
C++ Implementation details:
Same logic. s and p. Pointers i, j. istar, jmatch.
Edge case: string length 0.
If pattern is empty and text not -> False.
If text empty, pattern must be all *.
Wait, looking at the loop logic again for the empty string case.
If text is empty, while(i < len) doesn't run.
Then while(j < len and p[j] == '*') runs.
If pattern was *, j becomes len. Returns True.
If pattern was ?, loop doesn't run, outer loop doesn't run, but j is 0, len is 1. Returns False.
Wait, if text is empty and pattern is ?, it should be False. ? needs a char.
If text is empty and pattern is a, False.
If text is empty and pattern is *, True.
The greedy logic handles empty text correctly via the cleanup loop at the end.
Okay, plan is solid. I will write the response now.
Here are implementations of wildcard pattern matching in both Python and C++.
The algorithm used is the Greedy Approach with Backtracking. This is generally preferred over Dynamic Programming because it optimizes space complexity to O(1) (or O(m+n) depending on implementation details) compared to the O(m×n) space required for a standard DP table.
The Logic
We iterate through the text and the pattern using two pointers.
- Match: If characters match, or the pattern has a
?, advance both pointers.
- Wildcard (
*): If we encounter a *, we mark the position of the * in the pattern and the current position in the text. We assume the * matches an empty sequence initially.
- Mismatch: If characters do not match:
- Check if we have encountered a
* previously.
- If yes, backtrack: The previous
* must swallow the current character in the text. We move the text pointer forward and reset the pattern pointer to the position after the *.
- If no
* was found previously, the match fails.
Python Implementation
def is_match(text, pattern):
"""
Returns True if the text matches the wildcard pattern.
'?' Matches any single character.
'*' Matches any sequence of characters (including empty).
"""
# Pointers for text and pattern
t_ptr = 0
p_ptr = 0
# Variables to store the position of '*' in pattern and
# the corresponding position in text
star_idx = -1
match_idx = 0
len_t = len(text)
len_p = len(pattern)
while t_ptr < len_t:
# Case 1: Characters match or pattern has '?'
if p_ptr < len_p and (pattern[p_ptr] == text[t_ptr] or pattern[p_ptr] == '?'):
t_ptr += 1
p_ptr += 1
# Case 2: Pattern has '*'
elif p_ptr < len_p and pattern[p_ptr] == '*':
star_idx = p_ptr # Record index of '*'
match_idx = t_ptr # Record current text index
p_ptr += 1 # Move pattern pointer forward (assume * matches empty)
# Case 3: Mismatch, but we have a previous '*' to fall back to
elif star_idx != -1:
# Backtrack: the * must include the current character in text
p_ptr = star_idx + 1 # Reset pattern pointer to after the '*'
match_idx += 1 # Advance the text index that the '*' consumes
t_ptr = match_idx # Update current text pointer
# Case 4: Mismatch and no '*' to recover
else:
return False
# After processing all text, check if remaining pattern characters are '*'
# e.g., text="abc", pattern="a***" -> Valid
while p_ptr < len_p and pattern[p_ptr] == '*':
p_ptr += 1
# If pattern pointer reached end, it's a match
return p_ptr == len_p
# --- Test Cases ---
if __name__ == "__main__":
test_cases = [
("adceb", "*a*b", True),
("aa", "a", False),
("aa", "*", True),
("cb", "?a", False),
("mississippi", "m??*ss*?i*pi", False),
("abcdef", "abc?ef", True),
("abc", "abc", True),
("", "*", True),
("", "?", False)
]
for text, pattern, expected in test_cases:
result = is_match(text, pattern)
print(f"Text: '{text}', Pattern: '{pattern}' -> {result} (Expected: {expected})")
C++ Implementation
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isMatch(const string& text, const string& pattern) {
int tLen = text.length();
int pLen = pattern.length();
int tPtr = 0; // Pointer for text
int pPtr = 0; // Pointer for pattern
int starIdx = -1; // Index of '*' found in pattern
int matchIdx = 0; // Index in text matching the '*'
while (tPtr < tLen) {
// Case 1: Characters match or pattern is '?'
if (pPtr < pLen && (pattern[pPtr] == text[tPtr] || pattern[pPtr] == '?')) {
tPtr++;
pPtr++;
}
// Case 2: Pattern has '*'
else if (pPtr < pLen && pattern[pPtr] == '*') {
starIdx = pPtr; // Record star position
matchIdx = tPtr; // Record text position
pPtr++; // Try to match empty sequence first
}
// Case 3: Mismatch, but we have a star to fall back to
else if (starIdx != -1) {
// Backtrack: make the star consume the current text char
pPtr = starIdx + 1;
matchIdx++;
tPtr = matchIdx;
}
// Case 4: Mismatch and no star available
else {
return false;
}
}
// Check for remaining characters in pattern
while (pPtr < pLen && pattern[pPtr] == '*') {
pPtr++;
}
return pPtr == pLen;
}
int main() {
vector<tuple<string, string, bool>> tests = {
{"adceb", "*a*b", true},
{"aa", "a", false},
{"aa", "*", true},
("cb", "?a", false},
{"abcdef", "abc?ef", true}
};
for (const auto& test : tests) {
string t = get<0>(test);
string p = get<1>(test);
bool exp = get<2>(test);
bool res = isMatch(t, p);
string resStr = res ? "True" : "False";
string expStr = exp ? "True" : "False";
cout << "Text: \"" << t << "\", Pattern: \"" << p << "\" -> "
<< resStr << " (Expected: " << expStr << ")" << endl;
}
return 0;
}
Complexity Analysis
- Time Complexity: O(N×M) in the worst case, where N is the length of the text and M is the length of the pattern. This happens in scenarios like matching
text = "aaaaaab" against pattern = "*b" (the backtracking logic runs repeatedly). In average cases, it is typically linear O(N.