Find Longest Substring which is Prefix, Suffix and Present Inside String in Python



Suppose we have a given string, we have to find the largest sub-string which is a prefix, a suffix and a sub-string of that given string. If there is no such substring, then return -1.

So, if the input is like "languagepythonlanguageinterestinglanguage", then the output will be "language"

To solve this, we will follow these steps −

  • Define a function get_lps() . This will take string

  • n := size of string

  • long_pref_suff := an array of size n, and fill with 0

  • size := 0, long_pref_suff[0] := 0, i := 1

  • while i

    • if string[i] is same as string[size], then

      • size := size + 1

      • long_pref_suff[i] := size

      • i := i + 1

    • otherwise,

      • if size is not same as 0, then

        • size := long_pref_suff[size - 1]

      • otherwise,

        • long_pref_suff[i] := 0

        • i := i + 1

  • return long_pref_suff

  • From the main method, do the following −

  • long_pref_suff := get_lps(string)

  • n := size of string

  • if long_pref_suff[n - 1] is same as 0, then

    • return -1

  • for i in range 0 to n - 1, do

    • if long_pref_suff[i] is same as long_pref_suff[n - 1], then

      • return substring of string[from index 0 to long_pref_suff[i]]

  • if long_pref_suff[long_pref_suff[n - 1] - 1] is same as 0, then

    • return -1

  • otherwise,

    • return substring of string[from index 0 to long_pref_suff[long_pref_suff[n - 1] - 1]]

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def get_lps(string):
   n = len(string)
   long_pref_suff = [0 for i in range(n)]
   size = 0
   long_pref_suff[0] = 0
   i = 1
   while (i 

Input

"languagepythonlanguageinterestinglanguage"

Output

language
Updated on: 2020-08-20T07:47:16+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements