Problem · Dynamic Programming

Longest Common Substring

Learn this problem
MediumxAI logoxAIFULLTIMEOA

Problem statement

Given strings first and second, return the length of their longest common substring.

A substring occupies consecutive positions in its original string. If the strings share no character, return 0.

Function

longestCommonSubstring(first: String, second: String) → int

Examples

Example 1

first = "ABABC"second = "BABCA"return = 4

BABC appears consecutively in both strings.

Example 2

first = "abc"second = "def"return = 0

The strings share no character.

Constraints

  • 0 <= first.length, second.length <= 3000.
  • Both strings contain only printable ASCII characters.
  • An empty string has no non-empty substring.

More xAI problems

drafts saved locally
public int longestCommonSubstring(String first, String second) {
    // Write your code here.
}
first"ABABC"
second"BABCA"
expected4
checking account