Find Longest Common Substring from More Than Two Strings in Python



The substrings are the sequence of characters that appear within the string. While working with multiple strings, it is useful to find the longest common substring.

There are various ways to find the longest common substring from more than two strings. one of the most common approach is using the dynamic programming. Let's dive into the article to learn more about this task.

Using Dynamic Programming

In this approach, we are going to use the dynamic programming (DP), Here we compare the strings pairwise (starting with first two strings), we find their longest common substring using a DP table.

If two characters match at a certain position, we extend the current matching substring by adding one to the value from the previous matching position. Once we find the longest common substring of the first two strings, we repeat the process with this result and the next string in the list, and so on, until all the strings are compared.

The final result will be the longest substring that appears in all of the given strings.

Example 1

Let's look at the following example, where we are going to consider the basic usage with common substrings.

def demo(strs):
    def lcs(x1, x2):
        m, n = len(x1), len(x2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        a, b = 0, 0
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if x1[i - 1] == x2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                    if dp[i][j] > a:
                        a = dp[i][j]
                        b = i
        return x1[b - a: b]
    common_substr = strs[0]
    for i in range(1, len(strs)):
        common_substr = lcs(common_substr, strs[i])
    return common_substr
str1 = ["1123212", "2311232", "2112312"]
print(demo(str1))

The output of the above program is as follows -

1123

Example 2

Consider the another scenario, where we are going to take no common substrings and observing the output.

def demo(strs):
    def lcs(x1, x2):
        m, n = len(x1), len(x2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        a, b = 0, 0
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if x1[i - 1] == x2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                    if dp[i][j] > a:
                        a = dp[i][j]
                        b = i
        return x1[b - a: b]
    common_substr = strs[0]
    for i in range(1, len(strs)):
        common_substr = lcs(common_substr, strs[i])
    return common_substr
str1 = ["TP", "TutorialsPoint", "Welcome"]
result = demo(str1)
print(f"'{result}'")

The following is the output of the above program -

''
Updated on: 2025-05-08T11:00:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements