Regex matcher with starred groups

0
Sign in

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".

Reconstructed from the reported question; details may differ from what interviewers ask.

AmazonCodingHard

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.