AlgoInsight

DSA problem

Wildcard Matching

HardString DPPattern: String DPtop300MetaMicrosoftGoogleAmazonBloomberg

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

The matching should cover the entire input string (not partial). This is the simpler cousin of regular expression matching: * here behaves like .* from regex, and there is no concept of "zero or more of the previous character".

Naive backtracking explores every possible split of *, producing exponential blow-up on inputs like s = "aaaaaaab", p = "*a*a*a*a*b". Dynamic programming systematically resolves the overlap.

Define dp[i][j] as a boolean meaning "s[0..i) matches p[0..j)". The recurrences:

Initialize dp[0][0] = true and let leading * characters in the pattern continue to match the empty string. The algorithm runs in O(m * n) time and O(m * n) space (compressible to O(n)). A greedy two-pointer alternative runs in average linear time but the DP is the canonical, easy-to-verify approach.

Examples

Example 1
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the full string "aa". A wildcard would be needed to absorb the extra character.
Example 2
Input: s = "aa", p = "*"
Output: true
Explanation: "*" matches any sequence, including the two-character string "aa".
Example 3
Input: s = "cb", p = "?a"
Output: false
Explanation: "?" matches "c" but the literal "a" must match "b", which fails.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringdynamic-programminggreedy

Browse all DSA problems