Understanding and Solving Regular Expression Matching

Regular expressions, colloquially known as regex, are a foundational part of modern computing. They're a staple in string pattern matching, offering a robust way to recognise sequences of characters. LeetCode's Regular Expression Matching problem explores the mechanics of two special characters in regex: . and *.
This is considered a 'hard' coding problem, and you would be incredibly unlucky to get presented with this during an interview. Nevertheless, a little knowledge will help, so let's unravel this challenge.
Understanding the Problem
Problem Statement
Given an input string (s) and a pattern (p), implement regular expression matching with support for . and *.
.matches any single character,*matches zero or more of the preceding element.
The match must cover the entire input string. We assume a valid pattern made from the problem's permitted characters: each * follows a valid atom, and consecutive stars such as a** are outside the contract.
Examples
s = "aa",p = "a". Returnsfalse.s = "aa",p = "a*"Returnstrue.
This is a deliberately small matching language: lowercase English letters, . and *. There are no character classes, capture groups, escapes, or alternatives such as a|b. JavaScript's RegExp is the tool to reach for when you need those features; here, we're working out the branching choices for this restricted problem.
Solution: Recursive Approach
A recursive solution breaks down the problem into simpler versions of itself. At every step, we can match a piece of the string against a piece of the pattern until we either have a match, or we otherwise run out of string and/or pattern.
A Solution Using TypeScript
const isMatch = (s: string, p: string): boolean => {
// Base case
if (!p.length) return !s.length;
// Check if the first characters match (or if pattern has a '.')
const firstMatch = s.length > 0 && (s[0] === p[0] || p[0] === '.');
// Check for a '*' at the second position in the pattern
if (p.length >= 2 && p[1] === '*') {
return (
// Try not using '*' (i.e., use it to represent zero occurrence)
isMatch(s, p.substring(2)) ||
// Use '*' to represent one or more occurrence
(firstMatch && isMatch(s.substring(1), p))
);
}
return firstMatch && isMatch(s.substring(1), p.substring(1));
};How It Works
Base Case:
If the patternpis empty, then the input stringsshould also be empty for a successful match.First Character Match:
Next, we check if the first characters of the string and pattern match. They match if they are the same or if the pattern has a..Handling
If the second character in the pattern is*:*, we have two choices:- Assume
*represents zero occurrences of the preceding element and match the string with the remaining pattern. - Assume
*represents one occurrence (or more) and move to the next character in the string but use the same pattern. - If there is no
*, we just move to the next characters in both the string and the pattern.
Walking the Solution Step‑by‑Step
Take s = "aab" and p = "c*a*b".
- With
s = "aab"andp = "c*a*b", skipc*by matching the same string againsta*b. Zero copies ofcis allowed. - At
a*b, skippinga*would leaveb, which cannot match the firsta. Consume oneainstead, keepinga*bas the pattern. - Repeat that step for the second
a. The remaining string is nowb; skipa*and compare it withb. - The two
bcharacters match. Both remaining strings are empty, so the base case returnstrue.
Recursive Solution vs. Dynamic Programming
A recursive solution mirrors the shape of the problem nicely: compare the current character, then decide what to do when the next pattern token is *. That makes it a good teaching version, but repeated subproblems can make it expensive.
The recursive version can revisit the same remaining string and pattern through several different choices of how many characters each star consumes. A late failure is particularly unhelpful: we may explore lots of branches only to discover that none can match the final letter. Its worst‑case search grows exponentially, and each substring also creates another string value. I'd keep it as a way to understand the choices, rather than leave it as the final solution.
Remembering Which Positions Match
We can keep the same decisions without slicing either string. Let match(i, j) answer one question: does the input from position i onwards match the pattern from position j onwards? The original strings stay put. Only the two indices change.
There are two choices when p[j + 1] is *. Skip the whole atom‑and‑star pair with match(i, j + 2), or consume one matching input character with match(i + 1, j). The second choice keeps the pattern position because the star may consume another character. Without a star, both indices advance by one. Reaching the end of the pattern succeeds only if we've also reached the end of the input.
const isMatchMemo = (s: string, p: string): boolean => {
const width = p.length + 1;
const memo = new Array<boolean | undefined>((s.length + 1) * width);
const match = (i: number, j: number): boolean => {
const key = i * width + j;
const cached = memo[key];
if (cached !== undefined) return cached;
let result: boolean;
if (j === p.length) {
result = i === s.length;
} else {
const firstMatch = i < s.length && (p[j] === s[i] || p[j] === '.');
result = p[j + 1] === '*'
? match(i, j + 2) || (firstMatch && match(i + 1, j))
: firstMatch && match(i + 1, j + 1);
}
memo[key] = result;
return result;
};
return match(0, 0);
};The array stores one answer for each pair of positions. width leaves room for every pattern position, including the position just after its last character, and i * width + j gives each pair its own slot. Checking cached !== undefined matters: a remembered false is just as useful as a remembered true. A truthiness check would quietly throw away half the point of the cache.
What the Cache Changes
If the input has m characters and the pattern has n, there are at most (m + 1) * (n + 1) pairs. Each pair is evaluated once, with a constant amount of work and at most two recursive calls. That gives O((m + 1)(n + 1)) time and memo storage, usually written as O(mn) for non‑empty inputs. The call stack takes another O(m + n) space because each recursive step advances at least one index.
This is top‑down dynamic programming, not a separate matching rule. Every successful branch follows the same choices as the first version; we simply reuse an answer when another branch reaches the same pair. LeetCode limits both strings to 20 characters, so recursion depth is modest here. For much larger inputs, an iterative table would avoid relying on the JavaScript call stack.
Edge Cases to Cover
These checks cover full matching, skipping a starred atom, consuming it repeatedly, and failing after an apparently promising prefix. They can run immediately after the memoised function. The final case uses an empty input as an additional check of the base case; the published LeetCode inputs themselves have lengths between 1 and 20.
const examples: Array<[string, string, boolean]> = [
['aa', 'a', false],
['aa', 'a*', true],
['ab', '.*', true],
['aab', 'c*a*b', true],
['mississippi', 'mis*is*p*.', false],
['ab', '.*c', false],
['', 'a*b*', true],
];
for (const [input, pattern, expected] of examples) {
const actual = isMatchMemo(input, pattern);
if (actual !== expected) {
throw new Error(`Unexpected match for ${JSON.stringify([input, pattern])}`);
}
}For a separate cross‑check, I compared generated valid patterns with a JavaScript RegExp anchored at both ends. That comparison uses only lowercase letters, dots, and valid stars, so JavaScript‑specific features don't change what a match means. It's useful evidence alongside the worked cases, not a reason to widen this function's supported grammar. A leading star or consecutive stars such as a** remain invalid input.
Wrapping Up
The first version makes the choices visible. The memoised version keeps those choices and stops paying for them more than once. I'd work through the recursive example to understand the rule, then use the indexed version for the submission.
Postscript
November 2026: I've added the memoised version so you can follow the same matching decisions without repeatedly exploring the same positions. The examples now include executable checks, and I've compared generated valid patterns with fully anchored JavaScript regular expressions.