Search⌘ K
AI Features

Solution: Longest Common Subsequence

Explore how to solve the longest common subsequence problem by applying dynamic programming with a top-down memoization approach. Understand the use of a 2D table to store intermediate results, reducing redundant calculations and optimizing both time and space complexity for this common coding interview pattern.

Statement

Suppose you are given two strings. You need to find the length of the longest common subsequence between these two strings.

A subsequence is a string formed by removing some characters from the original string while maintaining the relative position of the remaining characters. For example, “abd” is a subsequence of “abcd”, where the removed character is “c”.

If there is no common subsequence, then return 0.

Constraints:

  • 11 \leq str1.length 500\leq 500
  • 11 \leq str2.length 500\leq 500
  • str1 and str2 contain only lowercase English characters.

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive approach

A naive approach would be to compare the characters of both strings based on the following rules:

  • If the current characters of both strings ...