Regular Expression Matching

Hard · Backtracking · String · Dynamic Programming · Recursion

Problem

Given a string s and a pattern p, decide whether the pattern matches the whole of s (not just part of it). The pattern supports two special characters:

Return True if p matches all of s, and False otherwise.

Examples

Input: s = "abbbc", p = "ab*c"
Output: true

b* absorbs the three b’s, and a and c match themselves.

Input: s = "ac", p = "a.c"
Output: false

The dot must consume exactly one character, so the pattern needs three characters.

Input: s = "xyz", p = ".*z"
Output: true

.* covers xy and the final z matches literally.

Constraints

Approaches

Follow-up

Real regex engines compile the pattern into an automaton: Thompson’s construction gives an NFA that is simulated in O(m · n) without backtracking. Engines that backtrack instead can take exponential time on patterns like (a*)*b, which is the cause of “ReDoS” attacks.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…