← Questions

Regex matcher with starred groups

0
AmazonCoding

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 unit x just 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 around O(len(s) * len(pattern)), about 10^6 steps.
  • 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 s with 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

dynamic programming · strings · parsing

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding