Longest common subsequence

Dynamic Programming DP on strings Hard
  • This problem, often known as the Longest Common Subsequence (LCS) problem, underlies the logic of many diff utilities and version control systems like Git
  • The diff tools use this problem to compare different versions of code or text files, and find the minimum number of changes needed to transform one version to another
  • This allows developers to efficiently track and manage changes in their projects over time

Given two strings str1 and str2, find the length of their longest common subsequence.


A subsequence is a sequence that appears in the same relative order but not necessarily contiguous and a common subsequence of two strings is a subsequence that is common to both strings.

Examples:

Input: str1 = "bdefg", str2 = "bfg"

Output: 3

Explanation: The longest common subsequence is "bfg", which has a length of 3.

Input: str1 = "mnop", str2 = "mnq"

Output: 2

Explanation: The longest common subsequence is "mn", which has a length of 2.

Input: str1 = "abc", str2 = "dafb"

Constraints

  • n=str1.length
  • m=str2.length
  • 1<= n, m <=103
  • str1 and str2 are in lowercase alphabet

Hints

  • Define dp[i][j] as the length of the LCS of the first i characters of str1 and the first j characters of str2.
  • If str1[i-1] == str2[j-1], the LCS extends dp[i][j]=1+dp[i−1][j−1]. Otherwise, we take the maximum LCS found by excluding either character dp[i][j]=max(dp[i−1][j],dp[i][j−1])

Company Tags

Goldman Sachs OYO Rooms Swiggy IBM Byju's Databricks Instacart Bain & Company Dropbox Walmart Broadcom Zomato KPMG Square Rakuten Pinterest Zynga Nutanix Bungie JPMorgan Chase Etsy Epic Systems PwC GE Healthcare McKinsey & Company Google Microsoft Amazon Meta Apple Netflix Adobe