← Microsoft bank

Microsoft · Question 70 · Dynamic Programming

Regular Expression Matching

Dynamic ProgrammingJavacode⏱ O(m×n)💾 O(m×n)
Product-based

Problem

Implement regex matching with. (any char) and * (zero or more of previous char).

Approach

DP over both prefixes; '*' skips or consumes a matching char.

Time O(m×n)Space O(m×n)

How it works

  1. 1Empty pattern matches empty string (plus a* cases).
  2. 2'*' skips its char or consumes one matching char.
  3. 3Other positions need a direct or '.' match.

Sample input / output

Input:
aa
a*
Output:
true

Constraints

1 <= s, p lengths <= 20.

Solution — read it, then walk it

Time O(m×n)Space O(m×n)Loops 3Branches 4Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yes↻ repeat↻ repeat↻ repeatyesnoyes↻ repeatyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static booleanisMatch(String s, String p)DEFINE m = s.length(), n =p.length()DEFINE [][] dp = newboolean[m + 1][n + 1]dp[0][0] = truefor (int j = 2; j <=n; j++)if (p.charAt(j - 1) =='*')dp[0][j] = dp[0][j - 2]for (int i = 1; i <=m; i++)for (int j = 1; j <=n; j++)if (p.charAt(j - 1) =='.' || p.charAt(j - 1)== s.charAt(i - 1))dp[i][j] = dp[i - 1][j - 1]else if (p.charAt(j -1) == '*')dp[i][j] = dp[i][j - 2]if (p.charAt(j - 2) =='.' || p.charAt(j - 2)== s.charAt(i - 1))dp[i][j] |= dp[i - 1][j]RETURN dp[m][n]DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)String s = sc.next();String p = sc.next()System.out.println(isMatch(s,p))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits