00:00

Problem Statement

Input/Output Examples

Visual Explanation

A star cell is true if the star matches nothing (the cell to the left) or one more character (the cell above). Any other pattern character copies the diagonal cell when it matches the current string character.

Approaches

The DP table checks every pair of prefixes. The greedy approach scans once and backtracks only to the most recent star.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string and m the length of the pattern. The table has (n + 1) × (m + 1) cells; the greedy scan uses constant memory and is fast on typical patterns.

Interview Tips and Recommended Approach

  • Handle leading stars. They allow matches against the empty prefix, so the first row needs special initialisation.
  • Collapse repeated stars. ** behaves like *, which can simplify the pattern first.
  • Do not confuse with regex. In regex, * repeats the previous character; here it matches any sequence.
  • Explain the greedy shortcut. Backtracking to only the last star is the key insight.

Recommended Approach: Dynamic Programming Table

Why: it states each rule of the problem directly as a recurrence, which makes it hard to get wrong and easy to explain, before discussing the constant-space greedy version.