AlgoInsight

DSA problem

Regular Expression Matching

HardString DPPattern: String DPtop600MetaGoogleMicrosoftAmazonBloomberg

Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:

The matching should cover the entire input string (not partial). The crucial difference from wildcard matching is that * here binds to the preceding character (or .), and "zero or more" means we can erase the previous element entirely.

A naive recursion explores many branches; pinning down a polynomial algorithm requires careful state design. Define dp[i][j] as a boolean meaning "s[0..i) matches p[0..j)". The recurrences:

Initialize dp[0][0] = true and seed the first row by repeatedly trying to drop x* pairs that match the empty string. Total cost: O(m * n) time and O(m * n) space, easily compressible to two rows.

Examples

Example 1
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the full string "aa".
Example 2
Input: s = "aa", p = "a*"
Output: true
Explanation: "a*" means zero or more of the preceding letter "a". Two occurrences of "a" satisfy the pattern.
Example 3
Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means zero or more of any single character; here it matches the two-character string "ab".

Constraints

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

stringdynamic-programmingrecursion

Browse all DSA problems