835. Find the longest common substring of two texts
To spot copied passages between a training document and a benchmark item, you look for the longest stretch of characters they share exactly.
Write longest_common_substring(a, b) that returns the longest string that appears as a contiguous substring of both a and b. If several have the same maximum length, return the one that ends earliest in a. If none exist, return "".
def longest_common_substring(a, b)Example 1
Input: longest_common_substring("abcdef", "zcdemf")
Output: "cde"
Example 2
Input: longest_common_substring("abc", "xyz")
Output: ""
Constraints
len(a),len(b)<= 2,000
Hint 1
Match extends the diagonal by 1.
Hint 2
Mismatch resets to 0.
Hint 3
Remember the end index, not just the length.
Common mistakes
- Using the subsequence recurrence and returning non-contiguous text.
- Slicing with off by one indices when rebuilding the answer.
- Allocating a full 2D table for very long strings.
Understand the idea
Longest common substring and longest common subsequence look alike but differ in one rule. For the subsequence, a mismatch takes the max of the left and upper cells; for the substring, a mismatch drops to 0 because the shared run is broken. With "abcdef" and "zcdemf" the run c, d, e builds L values 1, 2, 3, then f after m restarts at 1.