Regex matcher with starred groups
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests dynamic programming, strings and parsing.
Implement a small regex engine for a text-processing pipeline. Write is_match(s: str, pattern: str) -> bool. It returns True only when the whole string s matches pattern.
The pattern uses these rules:
- It contains only lowercase English letters,
.,*,(, and). - A letter matches itself.
.matches exactly one lowercase letter. -
x*matches zero or more copies of the single unitxjust before the star. -
( ... )groups its contents into one unit. A*after)repeats the whole group, so(ab)*matches"","ab","abab", and so on. A group without a star matches its contents once. - Groups are never nested, and a
*never appears inside a group. Every*follows a letter, a., or a).
Constraints: 0 <= len(s) <= 1000, 0 <= len(pattern) <= 1000, and s contains only lowercase letters.
Example 1
s = "zebeb", pattern = "(ze)*(be)*"
Output: False
(ze)* can take "ze" and (be)* can take "be", but the final "b" is only part of a group, and a starred group repeats only whole copies. No split works.
Example 2
s = "rrtuvtuvw", pattern = "r*(tuv)*w"
Output: True
r* matches "rr", (tuv)* matches "tuvtuv", and w matches "w".
Clarifying questions
- Can a group contain
.as well as letters? - Is an empty group
()possible, and what does()*match? - Does an empty pattern match only the empty string?
- Can the input pattern be assumed valid, or should malformed patterns raise?
What a strong answer covers
- Parses the pattern into units first: a letter,
., or a group string, each with a starred flag. - Runs a DP over
(position in s, unit index): an unstarred unit must match its full length at that position; a starred unit either skips or matches one copy and stays on the same unit. - Matches a group copy by comparing its characters with
s, allowing.; total work stays aroundO(len(s) * len(pattern)), about10^6steps. - Explains why greedy matching fails (a starred group that takes too much leaves nothing for what follows) and why memoization fixes the backtracking blow-up.
- Tests both examples, empty
swith an all-starred pattern,.*, and a group that partly matches at the end.
Follow-ups
- Support nested groups.
- Add
+and?. - Return the matched spans of each group.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
