Longest Common Substring
Given two strings, return their longest common substring: the longest string that appears contiguously in both. When several share the longest length, return the one that starts earliest in the first string. Two strings with nothing in common give "".
This is not the longest common subsequence: "abcde" and "ace" share the subsequence "ace" but no substring longer than one letter.
longestCommonSubstring("snowflake", "flakes") -> "flake"
longestCommonSubstring("abcxyz", "xyzabc") -> "abc" // "xyz" is as long but starts later in the first string
longestCommonSubstring("abc", "xyz") -> ""Hints
Hint 1
Let dp[i][j] be the length of the common suffix of the first i letters of one string and the first j of the other: dp[i-1][j-1] + 1 when the letters match, otherwise 0. The answer is the largest cell and where it sits.
Hint 2
Only the previous row is read, so keep two rows. Record a new best only on a strictly larger length while scanning the first string left to right, and the earliest start falls out for free.
Hint 3
A follow-up asks for better than O(m × n): binary search on the length with a set of rolling hashes of every window, and say what collisions cost.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.