The Wayback Machine - https://web.archive.org/web/20240804233400/https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/
Open In App

Longest repeating and non-overlapping substring

Last Updated : 05 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a string str, find the longest repeating non-overlapping substring in it. In other words find 2 identical substrings of maximum length which do not overlap. If there exists more than one such substring return any of them.

Examples: 

Input : str = "geeksforgeeks"
Output : geeks

Input : str = "aab"
Output : a

Input : str = "aabaabaaba"
Output : aaba

Input : str = "aaaaaaaaaaa"
Output : aaaaa

Input : str = "banana"
Output : an 
         or na

Naive Solution : The problem can be solved easily by taking all the possible substrings and for all the substrings check it for the remaining(non-overlapping) string if there exists an identical substring. There are O(n2) total substrings and checking them against the remaining string will take O(n) time. So overall time complexity of above solution is O(n3). 

Dynamic Programming : This problem can be solved in O(n2) time using Dynamic Programming. The basic idea is to find the longest repeating suffix for all prefixes in the string str. 

Length of longest non-repeating substring can be recursively
defined as below.

LCSRe(i, j) stores length of the matching and
            non-overlapping substrings ending 
            with i'th and j'th characters.

If str[i-1] == str[j-1] && (j-i) > LCSRe(i-1, j-1)
     LCSRe(i, j) = LCSRe(i-1, j-1) + 1, 
Else
     LCSRe(i, j) = 0

Where i varies from 1 to n and 
      j varies from i+1 to n

To avoid overlapping we have to ensure that the length of suffix is less than (j-i) at any instant. 
The maximum value of LCSRe(i, j) provides the length of the longest repeating substring and the substring itself can be found using the length and the ending index of the common suffix.

Below is the implementation of the recurrence. 

C++




// C++ program to find the longest repeated
// non-overlapping substring
#include<bits/stdc++.h>
using namespace std;
 
// Returns the longest repeating non-overlapping
// substring in str
string longestRepeatedSubstring(string str)
{
    int n = str.length();
    int LCSRe[n+1][n+1];
 
    // Setting all to 0
    memset(LCSRe, 0, sizeof(LCSRe));
 
    string res; // To store result
    int res_length  = 0; // To store length of result
 
    // building table in bottom-up manner
    int i, index = 0;
    for (i=1; i<=n; i++)
    {
        for (int j=i+1; j<=n; j++)
        {
            // (j-i) > LCSRe[i-1][j-1] to remove
            // overlapping
            if (str[i-1] == str[j-1] &&
                LCSRe[i-1][j-1] < (j - i))
            {
                LCSRe[i][j] = LCSRe[i-1][j-1] + 1;
 
                // updating maximum length of the
                // substring and updating the finishing
                // index of the suffix
                if (LCSRe[i][j] > res_length)
                {
                    res_length = LCSRe[i][j];
                    index = max(i, index);
                }
            }
            else
                LCSRe[i][j] = 0;
        }
    }
 
    // If we have non-empty result, then insert all
    // characters from first character to last
    // character of string
    if (res_length > 0)
        for (i = index - res_length + 1; i <= index; i++)
            res.push_back(str[i-1]);
 
    return res;
}
 
// Driver program to test the above function
int main()
{
    string str = "geeksforgeeks";
    cout << longestRepeatedSubstring(str);
    return 0;
}


Java




// Java program to find the longest repeated
// non-overlapping substring
 
class GFG {
 
// Returns the longest repeating non-overlapping
// substring in str
    static String longestRepeatedSubstring(String str) {
        int n = str.length();
        int LCSRe[][] = new int[n + 1][n + 1];
 
        String res = ""; // To store result
        int res_length = 0; // To store length of result
 
        // building table in bottom-up manner
        int i, index = 0;
        for (i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                // (j-i) > LCSRe[i-1][j-1] to remove
                // overlapping
                if (str.charAt(i - 1) == str.charAt(j - 1)
                        && LCSRe[i - 1][j - 1] < (j - i)) {
                    LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1;
 
                    // updating maximum length of the
                    // substring and updating the finishing
                    // index of the suffix
                    if (LCSRe[i][j] > res_length) {
                        res_length = LCSRe[i][j];
                        index = Math.max(i, index);
                    }
                } else {
                    LCSRe[i][j] = 0;
                }
            }
        }
 
        // If we have non-empty result, then insert all
        // characters from first character to last
        // character of String
        if (res_length > 0) {
            for (i = index - res_length + 1; i <= index; i++) {
                res += str.charAt(i - 1);
            }
        }
 
        return res;
    }
 
// Driver program to test the above function
    public static void main(String[] args) {
        String str = "geeksforgeeks";
        System.out.println(longestRepeatedSubstring(str));
    }
}
// This code is contributed by Rajput-JI


Python 3




# Python 3 program to find the longest repeated
# non-overlapping substring
 
# Returns the longest repeating non-overlapping
# substring in str
def longestRepeatedSubstring(str):
 
    n = len(str)
    LCSRe = [[0 for x in range(n + 1)]
                for y in range(n + 1)]
 
    res = "" # To store result
    res_length = 0 # To store length of result
 
    # building table in bottom-up manner
    index = 0
    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
             
            # (j-i) > LCSRe[i-1][j-1] to remove
            # overlapping
            if (str[i - 1] == str[j - 1] and
                LCSRe[i - 1][j - 1] < (j - i)):
                LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1
 
                # updating maximum length of the
                # substring and updating the finishing
                # index of the suffix
                if (LCSRe[i][j] > res_length):
                    res_length = LCSRe[i][j]
                    index = max(i, index)
                 
            else:
                LCSRe[i][j] = 0
 
    # If we have non-empty result, then insert
    # all characters from first character to
    # last character of string
    if (res_length > 0):
        for i in range(index - res_length + 1,
                                    index + 1):
            res = res + str[i - 1]
 
    return res
 
# Driver Code
if __name__ == "__main__":
     
    str = "geeksforgeeks"
    print(longestRepeatedSubstring(str))
 
# This code is contributed by ita_c


C#




// C# program to find the longest repeated
// non-overlapping substring
using System;
  
public class GFG {
  
// Returns the longest repeating non-overlapping
// substring in str
    static String longestRepeatedSubstring(String str) {
        int n = str.Length;
        int [,]LCSRe = new int[n + 1,n + 1];
  
        String res = ""; // To store result
        int res_length = 0; // To store length of result
  
        // building table in bottom-up manner
        int i, index = 0;
        for (i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                // (j-i) > LCSRe[i-1][j-1] to remove
                // overlapping
                if (str[i - 1] == str[j - 1]
                        && LCSRe[i - 1,j - 1] < (j - i)) {
                    LCSRe[i,j] = LCSRe[i - 1,j - 1] + 1;
  
                    // updating maximum length of the
                    // substring and updating the finishing
                    // index of the suffix
                    if (LCSRe[i,j] > res_length) {
                        res_length = LCSRe[i,j];
                        index = Math.Max(i, index);
                    }
                } else {
                    LCSRe[i,j] = 0;
                }
            }
        }
  
        // If we have non-empty result, then insert all
        // characters from first character to last
        // character of String
        if (res_length > 0) {
            for (i = index - res_length + 1; i <= index; i++) {
                res += str[i - 1];
            }
        }
  
        return res;
    }
  
// Driver program to test the above function
    public static void Main() {
        String str = "geeksforgeeks";
        Console.WriteLine(longestRepeatedSubstring(str));
    }
}
// This code is contributed by Rajput-JI


Javascript




<script>
// Javascript program to find the longest repeated
// non-overlapping substring
   
    // Returns the longest repeating non-overlapping
    // substring in str
    function longestRepeatedSubstring(str)
    {
        let n = str.length;
        let LCSRe = new Array(n+1);
        for(let i = 0; i < n + 1; i++)
        {
            LCSRe[i] = new Array(n+1);
        }
        for(let i = 0; i < n + 1; i++)
        {
            for(let j = 0; j < n + 1; j++)
            {
                LCSRe[i][j] = 0;
            }
        }
         
        let res = ""; // To store result
        let res_length = 0; // To store length of result
         
        // building table in bottom-up manner
        let i, index = 0;
        for (i = 1; i <= n; i++)
        {
            for (let j = i + 1; j <= n; j++)
            {
             
                // (j-i) > LCSRe[i-1][j-1] to remove
                // overlapping
                if (str[i-1] == str[j-1]
                        && LCSRe[i - 1][j - 1] < (j - i))
                {
                    LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1;
   
                    // updating maximum length of the
                    // substring and updating the finishing
                    // index of the suffix
                    if (LCSRe[i][j] > res_length)
                    {
                        res_length = LCSRe[i][j];
                        index = Math.max(i, index);
                    }
                }
                else
                {
                    LCSRe[i][j] = 0;
                }
            }
        }
   
        // If we have non-empty result, then insert all
        // characters from first character to last
        // character of String
        if (res_length > 0) {
            for (i = index - res_length + 1; i <= index; i++) {
                res += str.charAt(i - 1);
            }
        }
   
        return res;
    }
     
    // Driver program to test the above function
    let str= "geeksforgeeks";
    document.write(longestRepeatedSubstring(str));
     
    // This code is contributed by rag2127
</script>


Output

geeks

Time Complexity: O(n2) 
Auxiliary Space: O(n2)

References: 
https://www.geeksforgeeks.org/longest-common-substring/



Previous Article
Next Article

Similar Reads

Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Maximum number of times str1 appears as a non-overlapping substring in str2
Given two strings str1 and str2, the task is to find the maximum number of times str1 occurs in str2 as a non-overlapping substring after rearranging the characters of str2Examples: Input: str1 = "geeks", str2 = "gskefrgoekees" Output: 2 str = "geeksforgeeks"Input: str1 = "aa", str2 = "aaaa" Output: 2 Approach: The idea is to store the frequency of
7 min read
Kth non-overlapping Substring of length M after sorting given String lexicographically
Given string str of size N and two integers M and K (N is divisible by M), the task is to find the Kth non-overlapping substring of size M after sorting the given string lexicographically Examples: Input: str = "hwnriw", M = 3, K = 1Output: hinExplanation: Non overlapping substrings of size 3 after sorting are "hin" "rww". So 1st string is "hin" .
13 min read
Print Longest substring without repeating characters
Given a string, print the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. The desired time complexity is O(n) where n is the length of the string. Prerequisite: Length of
14 min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7 The desired time complexi
5 min read
Length of the longest substring without repeating characters
Given a string str, find the length of the longest substring without repeating characters. Example: Example 1:Input: "ABCDEFGABEF"Output: 7Explanation: The longest substring without repeating characters are "ABCDEFG", "BCDEFGA", and "CDEFGAB" with lengths of 7 Example 2:Input: "GEEKSFORGEEKS"Output: 7 Explanation: The longest substrings without rep
15+ min read
Longest Substring of A that can be changed to Substring of B in at most T cost
Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. Note: If multiple valid substrings are possible then
13 min read
Check if a string contains two non overlapping sub-strings "geek" and "keeg"
Given a string str, the task is to check whether the string contains two non-overlapping sub-strings s1 = "geek" and s2 = "keeg" such that s2 starts after s1 ends.Examples: Input: str = "geekeekeeg" Output: Yes "geek" and "keeg" both are present in the given string without overlapping.Input: str = "geekeeg" Output: No "geek" and "keeg" both are pre
3 min read
Count of non-overlapping sub-strings "101" and "010" in the given binary string
Given binary string str, the task is to find the count of non-overlapping sub-strings of either the form "010" or "101". Examples: Input: str = "10101010101" Output: 3 str[0..2] = "101" str[3..5] = "010" str[6..8] = "101"Input: str = "111111111111110" Output: 0 Approach: Initialize count = 0 and for every index i in the given string check whether t
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg