




Sponsored
Sponsored
This approach uses recursion with memoization to solve the problem efficiently. We recursively compare characters of the input string and the pattern, addressing special characters like '.' and '*'. The memoization is used to store results of sub-problems to avoid redundant calculations, which drastically improves the performance.
Time Complexity: O(m * n), where m and n are the lengths of the string and pattern, respectively. We solve every subproblem once and store the result.
Space Complexity: O(m * n) due to recursion stack and memoization storage.
1function isMatch(s, p) {
2    const memo = Array.from({ length: s.length + 1 }, () => Array(p.length + 1).fill(undefined));
3    function dfs(i, j) {
4        if (memo[i][j] !== undefined) {
5            return memo[i][j];
6        }
7        if (j === p.length) {
8            return i === s.length;
9        }
10        const match = i < s.length && (s[i] === p[j] || p[j] === '.');
11        if ((j + 1) < p.length && p[j + 1] === '*') {
12            memo[i][j] = dfs(i, j + 2) || (match && dfs(i + 1, j));
13            return memo[i][j];
14        }
15        if (match) {
16            memo[i][j] = dfs(i + 1, j + 1);
17            return memo[i][j];
18        }
19        memo[i][j] = false;
20        return false;
21    }
22    return dfs(0, 0);
23}The JavaScript solution uses a 2D array to memorize results of subproblems within the recursive process. This allows bypassing recalculations and adjusting decisions based on the appearance of special regex characters in the pattern.
This approach involves using a DP table to solve the problem by filling up a boolean matrix iteratively. This avoids recursion and stacks overhead, improving performance in certain scenarios. Each cell in the table represents whether the substring of the pattern matches the substring of the input.
Time Complexity: O(m * n) since we traverse the complete matrix.
Space Complexity: O(m * n) due to the DP table used to store subproblem solutions.
1The Python DP solution constructs a 2D boolean array where dp[i][j] signifies if the first i characters of the string match the first j characters of the pattern. The matrix is initialized with the base conditions and filled based on the characters in pattern string, iteratively updating for mismatches dictated by '*' or '.'.