You are given a string s of lower-case letters and a pattern p. The pattern may hold letters and two wildcards: ? stands for exactly one character, any one, and * stands for any run of characters, including none at all.
Return true if the pattern describes all of s, from its first character to its last, and false otherwise. Matching only part of s is not enough.
Example 1
Input: s = "abcbd", p = "a*bd" Output: true Why: the star takes "bc"
2 more examples and the constraints
Example 2
Input: s = "pq", p = "?" Output: false Why: one ? covers one letter, and s has two
Example 3
Input: s = "", p = "**" Output: true Why: both stars take nothing
Constraints
- 0 ≤ length of s, length of p ≤ 2,000
- s holds only lower-case English letters
- p holds only lower-case English letters,
?and*
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DP table over prefixesO(m·n)
- Greedy, back up to the last starO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 characters each | Verdict |
|---|---|---|---|
| DP table over prefixes | O(m·n) | Passes; easiest to prove | |
| Greedy, back up to the last star | O(m·n) worst | Best; usually near-linear |
m = length of s, n = length of p. The greedy work is for typical inputs; its worst case equals the table.
Edge cases to test
- Empty string. "" matches a pattern made only of stars, and the empty pattern, but not "?".
- Empty pattern. It matches only the empty string.
- A star that takes nothing. "cab" with "c*ab": the star must match the empty run.
- More ? than letters. "abc" with "*?*?*?*?" is false: four ? need four letters.
- Trailing stars. When s runs out, stars left in p still match; anything else left does not.
Common mistakes
- Returning true when s runs out without checking the rest of p is only stars.
- Backing up to the first star instead of the last one.
- Filling row 0 with True after a letter, so "" seems to match "*a".
How to talk through it
- 1Clarify. Must the whole string match? Can a star take nothing? Can s or p be empty?
- 2Name the subproblem. Does a prefix of s match a prefix of p? That gives an (m + 1) × (n + 1) table.
- 3Explain the star rule. Take nothing (left) or one more character (up). Letters and ? copy the diagonal.
- 4Offer the greedy. Back up only to the last star. O(1) space, near-linear on most inputs.
- 5Test out loud. Run the empty string against stars, an empty pattern, and a pattern with too many ?.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?