00:00

Problem Statement

Input/Output Examples

Visual Explanation

When the last characters of two prefixes match, they can extend the best common subsequence of the shorter prefixes. When they do not, the best answer comes from dropping one of the two characters.

Approaches

Both approaches use the same recurrence. One fills the table iteratively; the other recurses with a cache.

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 and m are the lengths of the strings. Each of the n × m states is computed once in constant time.

Interview Tips and Recommended Approach

  • Separate subsequence from substring. The longest common substring needs a different recurrence that resets to 0 on a mismatch.
  • Reconstruct the sequence if asked. Walk back from the bottom-right cell, following diagonal moves on matches.
  • Save memory with two rows. Each row depends only on the row above.
  • Know where it is used: diff tools and version control compare files with LCS-based algorithms.

Recommended Approach: Bottom-Up DP Table

Why: it is the textbook formulation, easy to trace by hand and straightforward to extend to reconstruct the subsequence itself.