Menu
CoddyTech

Longest Common Substring

You get two strings, s1 and s2. A substring is an unbroken run of letters taken from a string, such as ork from clockwork. Find the longest substring that s1 and s2 have in common and return its length. When no letter occurs in both strings, the answer is 0.

Function

longestCommonSubstring(s1: string, s2: string) → integer
s1string
the first string
s2string
the second string
Returnsinteger
the length of the longest block of letters found in both strings

Constraints

  • 1 ≤ s1.length ≤ 1000
  • 1 ≤ s2.length ≤ 1000
  • s1 and s2 consist of lowercase English letters.

Examples

Input
s1 = "clockwork"s2 = "workshop"
Output
4
Explanation
work closes clockwork and opens workshop, so it is a common substring of length 4, and no longer block appears in both.
challenge icon

Follow-up

Can you test whether a common substring of a given length L exists in about O(n + m) time with a rolling hash, and then binary search on L?

Reset code
def longestCommonSubstring(s1, s2):
    # Write code here

Test #1

Test #2

Test #3

Arguments

s1 = "clockwork"
s2 = "workshop"

Expected Output

4