Program to find length of longest repeating substring in a string in Python


Suppose we have a lowercase string s, we have to find the length of the longest substring that occurs at least twice in s. If we cannot find such string, return 0.

So, if the input is like s = "abdgoalputabdtypeabd", then the output will be 3, because the longest substring that occurs more than once is "abd".

To solve this, we will follow these steps −

  • Define a function lcs() . This will take s1, s2
  • n := minimum of size of s1 and size of s2
  • for i in range 0 to n - 1, do
    • if s1[i] is not same as s2[i], then
      • return substring of s1[from index 0 to i-1]
  • return substring of s1[from index 0 to n - 1]
  • From the main method, do the following −
  • suffixes := a new list
  • n := size of s
  • max_len := 0
  • for i in range 0 to n - 1, do
    • insert (substring of s[from index i to n - 1]) at the end of suffixes
  • sort the list suffixes
  • for each item a from suffixes and b from substring of suffixes[from index 1 to end], do
    • rtr := lcs(a, b)
    • if size of rtr > max_len, then
      • max_len := size of rtr
  • return max_len

Example

Let us see the following implementation to get better understanding −

def lcs(s1, s2):
   n = min(len(s1), len(s2))

   for i in range(n):
      if s1[i] != s2[i]:
         return s1[:i]
   return s1[:n]

def solve(s):
   suffixes = []
   n = len(s)
   max_len = 0

   for i in range(n):
      suffixes.append(s[i:n])

   suffixes.sort()

   for a, b in zip(suffixes, suffixes[1:]):
      rtr = lcs(a, b)

      if len(rtr) > max_len:
         max_len = len(rtr)

   return max_len

s = "abdgoalputabdtypeabd"
print(solve(s))

Input

"abdgoalputabdtypeabd"

Output

3

Updated on: 19-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements