← Uber bank

Uber · Question 75 · Dynamic Programming

Regular Expression Matching

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

Problem

Implement regular expression matching with support for '.' (any char) and '*' (zero or more of the previous char).

Approach

DP[i][j] = whether s[:i] matches p[:j]. A '*' either skips its char or consumes one more match; otherwise chars must match.

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

How it works

  1. 1Empty pattern matches only the empty string (plus a* cases).
  2. 2'*' means skip its char or consume 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; letters, '.' and valid '*' only.

Solution — read it, then walk it

Time O(m×n)Space O(m×n)Loops 3Branches 7Returns 4source · Python
Scroll sideways for wide charts — the view follows the active step.
yes↻ repeat↻ repeatyesnoyesno↻ repeatyesnoyes↻ repeat↻ repeatyesnoSTARTs, pm, n = len(s), len(p)dp = [[False] * (n + 1) for_ in range(m + 1)]dp[0][0] = Truefor j in range(2, n +1)if p[j - 1] == '*'dp[0][j] = dp[0][j - 2]DEFINE matches(i, j)if i == 0RETURN Falseif p[j - 1] == '.'RETURN TrueRETURN s[i - 1] == p[j - 1]for i in range(1, m +1)for j in range(1, n +1)if p[j - 1] == '*'dp[i][j] = dp[i][j - 2] or(matches(i, j - 1) and dp[i- 1][j])ELSEif matches(i, j)dp[i][j] = dp[i - 1][j - 1]RETURN dp[m][n]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)s = next(it); p = next(it)print(isMatch(s, p))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/30

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