Longest common substring

Dynamic Programming DP on strings Hard

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


A substring is a contiguous sequence of characters within a string.

Examples:

Input: str1 = "abcde", str2 = "abfce"

Output: 2

Explanation: The longest common substring is "ab", which has a length of 2.

Input: str1 = "abcdxyz", str2 = "xyzabcd"

Output: 4

Explanation: The longest common substring is "abcd", which has a length of 4.

Input: str1 = "abcdef", str2 = "ghijkl"

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 longest common substring ending at str1[i-1] and str2[j-1].
  • "If str1[i-1] == str2[j-1]: dp[i][j]=dp[i−1][j−1]+1 Otherwise, reset dp[i][j] = 0 (since a substring must be contiguous). "

Company Tags

Flipkart Databricks Cloudflare Bain & Company Roche Instacart Bloomberg Zynga Micron Technology Optum Docker Swiggy Etsy Dropbox Airbnb Cerner Johnson & Johnson Stripe Rakuten Alibaba Oracle Uber Activision Blizzard DoorDash Robinhood Google Microsoft Amazon Meta Apple Netflix Adobe