Bird
Raised Fist0
Interview Prepdp-lcs-stringhardGoogleFacebookAmazonMicrosoft

Regular Expression Matching

Choose your preparation mode4 modes available
📋
Problem

Imagine building a search engine that supports complex pattern queries with '.' and '*' wildcards, and you need to verify if a given text matches a pattern.

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 matching should cover the entire input string (not partial). Return true if s matches p, otherwise false.

1 ≤ s.length, p.length ≤ 1000s contains only lowercase English lettersp contains only lowercase English letters, '.' and '*'
Edge cases: Empty string s and empty pattern p → trueEmpty string s and pattern with only '*' (like 'a*') → truePattern with '*' at the start (invalid pattern) → should handle gracefully
</>
IDE
def isMatch(s: str, p: str) -> bool:public boolean isMatch(String s, String p)bool isMatch(string s, string p)function isMatch(s, p)
def isMatch(s: str, p: str) -> bool:
    # Write your solution here
    pass
class Solution {
    public boolean isMatch(String s, String p) {
        // Write your solution here
        return false;
    }
}
#include <string>
using namespace std;

bool isMatch(string s, string p) {
    // Write your solution here
    return false;
}
function isMatch(s, p) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: true for input s='aa', p='a'Failed to enforce full string match; pattern shorter than string but returned true.✅ Ensure that the entire string is matched by the pattern, not just a prefix.
Wrong: false for input s='aab', p='c*a*b'Did not handle '*' zero occurrence correctly, skipping 'c*' and 'a*'.✅ Add logic to try skipping '*' and consuming characters when matching.
Wrong: false for input s='', p='a*'Failed to initialize dp for patterns that can match empty string via '*'.✅ Initialize dp[0][j] = dp[0][j-2] when p[j-1] == '*'.
Wrong: true for input s='a', p='*a'Did not validate pattern correctness; '*' cannot be first character.✅ Add validation to reject patterns starting with '*'.
Wrong: false for input s='aaa', p='a*a'Used greedy matching consuming all 'a's leaving no match for last 'a'.✅ Try both skipping '*' and consuming characters in DP.
✓
Test Cases
t1_01basic
Input{"s":"aa","p":"a"}
Expectedfalse

Pattern 'a' does not match the entire string 'aa'.

t1_02basic
Input{"s":"aab","p":"c*a*b"}
Expectedtrue

Pattern 'c*a*b' matches 'aab' by interpreting 'c*' as empty, 'a*' as 'aa', and 'b' as 'b'.

t2_01edge
Input{"s":"","p":""}
Expectedtrue

Empty string matches empty pattern.

t2_02edge
Input{"s":"","p":"a*"}
Expectedtrue

Pattern 'a*' can match empty string by zero occurrences of 'a'.

t2_03edge
Input{"s":"a","p":"*a"}
Expectedfalse

Pattern starting with '*' is invalid and should not match any string.

t3_01corner
Input{"s":"aaa","p":"a*a"}
Expectedtrue

Pattern 'a*a' matches 'aaa' by 'a*' matching 'aa' and final 'a' matching last 'a'.

t3_02corner
Input{"s":"ab","p":".*c"}
Expectedfalse

Pattern '.*c' cannot match 'ab' because 'c' must match last char but string ends with 'b'.

t3_03corner
Input{"s":"aaa","p":"ab*a*c*a"}
Expectedtrue

Complex pattern matches 'aaa' by interpreting 'b*' as empty, 'a*' as 'aa', and final 'a'.

t4_01performance
Input{"_description":"n=1000 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

Input size n=1000 for s and p; O(m*n) DP solution must complete within 2 seconds.

Practice

(1/5)
1. What is the time complexity of the space-optimized bottom-up DP solution for the Delete Operation for Two Strings problem, where the input strings have lengths m and n respectively?
medium
A. O(m * n)
B. O(m + n)
C. O(m * n * log(m + n))
D. O(m^2 + n^2)

Solution

  1. Step 1: Identify nested loops over m and n

    The outer loop runs m times, inner loop runs n times, leading to m*n iterations.
  2. Step 2: Confirm no extra hidden factors

    Each iteration does O(1) work; no sorting or recursion overhead.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    DP table size m*n and each cell computed once [OK]
Hint: Nested loops over m and n -> O(m*n) [OK]
Common Mistakes:
  • Confusing linear with quadratic
  • Assuming sorting or recursion adds log factor
  • Ignoring nested loops
2. What is the time complexity of the space-optimized bottom-up DP solution for wildcard matching where m and n are the lengths of the input string and pattern respectively?
medium
A. O(m + n)
B. O(m * n)
C. O(2^(m + n))
D. O(m * n^2)

Solution

  1. Step 1: Identify loops in the DP code

    The code has nested loops: outer loop runs m times, inner loop runs n times.
  2. Step 2: Calculate total operations

    Each iteration does O(1) work, so total time is O(m * n).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    DP fills a table of size m by n once [OK]
Hint: Nested loops over string and pattern lengths imply O(m*n) [OK]
Common Mistakes:
  • Confusing with brute force exponential
  • Assuming linear time
  • Forgetting nested loops
3. What is the time complexity of the bottom-up DP solution for Word Break II that uses nested loops over the string and dictionary words, and concatenates sentences stored in dp arrays?
medium
A. O(n^3) due to nested loops and string concatenations
B. O(n^2 * m) because each substring is checked against dictionary words
C. O(2^n) because all segmentations are explored
D. O(n * m) where n = length of string, m = number of words in dictionary

Solution

  1. Step 1: Identify nested loops and operations

    Outer loop runs n times, inner loop over dictionary words m times, and for each match, concatenation of strings from dp arrays occurs.
  2. Step 2: Analyze concatenation cost

    Concatenation and copying sentences can cost up to O(n) each, and there can be O(n^2) substrings, leading to O(n^3) total time.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Nested loops plus string concatenations cause cubic time [OK]
Hint: String concatenation inside nested loops causes O(n^3) [OK]
Common Mistakes:
  • Confusing exponential brute force with DP complexity
  • Ignoring concatenation cost
4. Suppose you want to count palindromic substrings in a string where characters can be replaced any number of times (reusable characters). Which modification to the expand around center approach correctly handles this variant?
hard
A. No modification needed; the original expand around center approach already counts palindromes with replacements.
B. Modify expand to allow skipping mismatched characters to find palindromes with replacements.
C. Precompute all possible character replacements and run the original expand around center for each variant.
D. Use dynamic programming with memoization to store counts for substrings allowing character replacements.

Solution

  1. Step 1: Understand the variant

    Allowing character replacements means palindrome checks must consider substitutions, not exact matches.
  2. Step 2: Evaluate approaches

    Expand around center relies on exact matches; skipping mismatches breaks palindrome definition. Precomputing all variants is exponential. DP with memoization can track allowed replacements efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP can handle flexible palindrome definitions with substitutions [OK]
Hint: Exact match expansion fails when replacements allowed [OK]
Common Mistakes:
  • Assuming original approach works without changes
5. Suppose the problem is modified so that characters from s1 and s2 can be reused any number of times to form s3. Which of the following algorithmic changes correctly adapts the DP solution to this new requirement?
hard
A. Use the same DP but allow transitions to stay at the same indices in s1 or s2 when characters match, enabling reuse
B. No change needed; the original DP already handles reuse implicitly
C. Change the DP to a shortest path problem in a graph where edges represent character matches with reuse allowed
D. Modify the DP to consider infinite loops by adding a visited set to avoid cycles in recursion

Solution

  1. Step 1: Understand reuse impact

    Allowing reuse means indices in s1 and s2 can stay the same or move forward, potentially causing cycles.
  2. Step 2: Adapt algorithm

    To avoid infinite recursion or loops, the DP or recursion must track visited states to prevent cycles.
  3. Step 3: Evaluate options

    Modify the DP to consider infinite loops by adding a visited set to avoid cycles in recursion correctly adds a visited set to recursion to handle cycles; others either do not prevent cycles or incorrectly claim no change is needed.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Cycle detection is essential when reuse is allowed to ensure termination [OK]
Hint: Reuse allows cycles; track visited states to avoid infinite loops [OK]
Common Mistakes:
  • Assuming original DP handles reuse without modification
  • Trying to model reuse with simple DP transitions without cycle checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard