Simple Regex Compiler - Problem

Build a Simple Regex Compiler that takes a regular expression pattern and a test string, then determines if the string matches the pattern.

Your compiler must implement three key phases:

  • Phase 1: Parse the regex pattern and build a Non-deterministic Finite Automaton (NFA)
  • Phase 2: Convert the NFA to a Deterministic Finite Automaton (DFA)
  • Phase 3: Execute pattern matching by running the test string through the DFA

Supported regex operators:

  • * - Zero or more occurrences of the preceding character
  • + - One or more occurrences of the preceding character
  • ? - Zero or one occurrence of the preceding character
  • | - Alternation (OR operation)
  • . - Matches any single character
  • () - Grouping for operator precedence

Return true if the entire test string matches the pattern, false otherwise.

Input & Output

Example 1 — Basic Kleene Star
$ Input: pattern = "a*b", text = "aab"
Output: true
💡 Note: Pattern 'a*b' means zero or more 'a's followed by 'b'. Text 'aab' has 2 a's followed by b, which matches.
Example 2 — Plus Operator
$ Input: pattern = "a+b", text = "ab"
Output: true
💡 Note: Pattern 'a+b' requires one or more 'a's followed by 'b'. Text 'ab' has exactly 1 a followed by b.
Example 3 — Question Mark
$ Input: pattern = "a?b", text = "b"
Output: true
💡 Note: Pattern 'a?b' means zero or one 'a' followed by 'b'. Text 'b' has zero a's, which matches.

Constraints

  • 1 ≤ pattern.length ≤ 20
  • 1 ≤ text.length ≤ 1000
  • pattern contains only lowercase letters and operators: *, +, ?, |, ., ()
  • text contains only lowercase letters

Visualization

Tap to expand
INPUTPattern"a*b"Test String"aab"Regex pattern with Kleene starString to match against patternALGORITHM1Build NFA2NFA to DFA3Execute Match4Return ResultSubset construction algorithmconverts non-deterministic todeterministic state machineRESULTMatch FoundtruePattern 'a*b' successfullymatches string 'aab'(2 a's + 1 b)Key Insight:Converting non-deterministic finite automaton to deterministic eliminatesexponential backtracking, enabling linear-time pattern matching execution.TutorialsPoint - Simple Regex Compiler | NFA to DFA Conversion
Asked in
Google 25 Microsoft 20 Amazon 15 Meta 12
23.0K Views
Medium Frequency
~45 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen