Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Regular Expression Matching Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Regular Expression Matching

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

Implement regular expression matching.

In a regular expression:

  • a-z matches the corresponding character.
  • . matches any single character.
  • * matches zero or more of the preceding character.

The entire input string should be matched.

The function would take a string s and the regular expression pattern p.

Naive Approach

The naive approach is to use a brute force recursion-based approach. The recurrence is that if there were no Wildcard Characters, we can simply iterate on the string and check if the strings match or not. Else if there is a wildcard character, we will have to check all the possible suffixes of the text and check if they match with the pattern or not, all of which can be simply implemented using a brute force recursion based solution.

Analysis

  • Time Complexity: Exponential
  • Space Complexity: Exponential

Implementation

C++
bool isMatch (string s, string p) {
    if(p.empty()) {
		return s.empty();
	}
	bool match = true;
	if(s.empty() || (p[0] != s[0] && p[0] != '.')) {
		match = false;
	}
	if(p.size() == 1 || p[1] != '*') {
		return match && isMatch(s.substr(1), p.substr(1));
	} else {
		if(isMatch(s, p.substr(2))) {
			return true;
		} else {
			return (match && isMatch(s.substr(1), p));
		}
	}
}
Java
class Solution {
	boolean isMatch (String s, String p) {
	    if(p.length() == 0) {
			return s.length() == 0;
		}
		boolean match = true;
		if(s.length() == 0 || (p.charAt(0) != s.charAt(0) && p.charAt(0) != '.')) {
			match = false;
		}
		if(p.length() == 1 || p.charAt(1) != '*') {
			return match && isMatch(s.substring(1), p.substring(1));
		} else {
			if(isMatch(s, p.substring(2))) {
				return true;
			} else {
				return (match && isMatch(s.substring(1), p));
			}
		}
	}
}

Optimal Approach

We can observe in our naive solution that multiple function calls are getting repeated again and again. This gives us the idea to memoize these function calls to prevent them from getting repeated again and again. So, we use DP to memoize these function calls and solve the problem in polynomial time complexity.

Analysis

  • Time Complexity: O(|s| + |p|)
  • Space Complexity: O(|s| + |p|)

Implementation (Recursive)

C++
vector<vector<int>> dp;
bool solve(string s, string p) {
	if(p.empty()) {
		return s.empty();
	}
	bool match = true;
	if(s.empty() || (p[0] != s[0] && p[0] != '.')) {
		match = false;
	}
	if(dp[s.length()][p.length()] != -1) {
		return dp[s.length()][p.length()];
	}
	if(p.size() == 1 || p[1] != '*') {
		return  dp[s.length()][p.length()] = match && solve(s.substr(1), p.substr(1));
	} else {
		if(solve(s, p.substr(2))) {
			return true;
		} else {
			return dp[s.length()][p.length()] = (match && solve(s.substr(1), p));
		}
	}
}
bool isMatch (string s, string p) {
    dp.assign(s.length() + 1, vector<int> (p.length() + 1, -1));
	return solve(s, p);
}
Java
class Solution {
	Boolean dp[][];
	boolean solve(String s, String p) {
		if(p.length() == 0) {
			return s.length() == 0;
		}
		boolean match = true;
		if(s.length() == 0 || (p.charAt(0) != s.charAt(0) && p.charAt(0) != '.')) {
			match = false;
		}
		if(dp[s.length()][p.length()] != null) {
			return dp[s.length()][p.length()];
		}
		if(p.length() == 1 || p.charAt(1) != '*') {
			return  dp[s.length()][p.length()] = match && solve(s.substring(1), p.substring(1));
		} else {
			if(solve(s, p.substring(2))) {
				return true;
			} else {
				return dp[s.length()][p.length()] = (match && solve(s.substring(1), p));
			}
		}
	}
	boolean isMatch (String s, String p) {
	    dp = new Boolean[s.length() + 1][p.length() + 1];
		return solve(s, p);
	}
}

Implementation(Iterative)

C++
bool isMatch (string s, string p) {
    int n = s.size(), m = p.size();
	int dp[n + 1][m + 1];
	for(int i = 0; i <= n; i++) {
		dp[i][0] = 0;
	}
	dp[0][0] = 1;
	for(int i = 0; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			dp[i][j] = 0;
			if(p[j - 1] == '*') {
				if(j >= 2) {
					dp[i][j] |= dp[i][j - 2];
				}
				dp[i][j] |= (i && dp[i - 1][j] && j >= 2 && (s[i - 1] == p[j - 2] || p[j - 2] == '.'));
			}
			else{
				if(p[j - 1] == '.' && i) {
					dp[i][j] = dp[i - 1][j - 1];
				}
				else{
					if(i && s[i - 1] == p[j - 1]) {
						dp[i][j] = dp[i - 1][j - 1];
					}
					else {
						dp[i][j] = 0;
					}
				}
			}
		}
	}
	return dp[n][m];
}
Java
class Solution {
	boolean isMatch (String s, String p) {
		boolean dp[][] = new boolean[s.length() + 1][p.length() + 1];
        for(int i = 0; i <= s.length(); i++){
            for(int j = 0; j <= p.length(); j++){
                if(j == 0 && j == i) {
                    dp[i][j] = true;
				}
                else if(j == 0) {
                    dp[i][j] = false;
				}
                else if(i == 0 && p.charAt(j - 1) != '*') {
                    dp[i][j] = false;
				}
                else if(i == 0) {
                     dp[i][j] = dp[i][j - 2];
				}
                else {
                    if(p.charAt(j - 1) == '.' || s.charAt(i - 1) == p.charAt(j - 1)) {
                        dp[i][j] = dp[i - 1][j - 1];
                    }
                    if(p.charAt(j - 1) == '*'){
                        dp[i][j] = dp[i][j - 2];
						boolean match = ((p.charAt(j - 2) == '.' ||  p.charAt(j - 2) == s.charAt(i - 1)) && dp[i - 1][j]);
						dp[i][j] = dp[i][j] || match;
                    }
                }
            }
        }
        return dp[s.length()][p.length()];
	}
}
Related Content
Best Time to Buy and Sell Stocks
Best Time to Buy and Sell Stocks II
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV
Climbing Stairs
Coin Change
Collect Jewels
Decode Ways
Edit Distance (Levenshtein Distance)
Minimum Egg Drops
Longest Common Subsequence (LCS)
Longest Increasing Subsequence (LIS)
Longest Palindromic Substring (LPS)
Maximum path sum in matrix
Maximum Product Subarray
Maximum Sum Increasing Subsequence
Palindrome Partitioning
Palindrome Partitioning 2
Rod Cutting
Subset Sum
Subset Sum 2
Trapping Rain Water
Unique Paths
Wildcard Matching
Word Break
Word Break - II
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet