Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Wildcard pattern matching

Hard · Target 30 minutes · Dynamic programming · Type asked atGoogleMetaAmazon

Given a string s and a pattern p, return true if the pattern matches the whole of s. In the pattern, ? matches exactly one character, * matches any sequence of characters including the empty one, and any other character matches only itself.

Examples

InputOutputWhy
s = "adceb", p = "*a*b"trueThe first * matches nothing, the second "dce".
s = "cb", p = "?a"false? matches c, but a does not match b.
s = "", p = "*"true* matches the empty string.

Constraints

  • 0 ≤ s.length, p.length ≤ 2000
  • s: lowercase letters; p: lowercase letters, ? and *

Hints

Hint 1

match[i][j]: does p[:j] match s[:i]?

Hint 2

A star either matches nothing (match[i][j − 1]) or one more character (match[i − 1][j]).

Hint 3

match[0][j] is true only while p[:j] is all stars.

Where people lose marks

  • Looping over every length a star could absorb, which is O(n³).
  • Initialising match[0][j] to true for all j instead of only for leading stars.
  • Confusing * here with the regular-expression * that repeats the previous character.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.