00:00

Problem Statement

Input/Output Examples

Visual Explanation

Every character of s can always be skipped, which carries the count down. When it equals the next character of t, it can also be used, which adds the count from the diagonal.

Approaches

Both approaches use the skip-or-use recurrence. The first stores the whole table; the second keeps a single row.

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 s and m the length of t. Both approaches compute n × m values; the 1D version keeps only m + 1 of them.

Interview Tips and Recommended Approach

  • Initialise the empty target. There is exactly one way to form "", which is what seeds every count.
  • Use long. The number of ways grows combinatorially and can overflow an int.
  • Explain the backward loop. A forward loop would let one character of s count twice.
  • Relate it to LCS. Both tables walk two prefixes; here you count ways instead of measuring length.

Recommended Approach: 1D DP, Updated Backwards

Why: it needs only one array of length m + 1 and one simple update rule, and the backward loop is a reusable trick for knapsack-style counting.