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.
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 C++ implementation of the recurrence.
Time Complexity: O(n2)
Auxiliary Space: O(n2)
This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Longest Common Subsequence with at most k changes allowed
- Count all subsequences having product less than K
- Check if all people can vote on two machines
- Probability of Knight to remain in the chessboard
- Number of palindromic paths in a matrix
- All ways to add parenthesis for evaluation
- Count distinct occurrences as a subsequence
- Find minimum sum such that one of every three consecutive elements is taken
- Count Distinct Subsequences
- A Space Optimized DP solution for 0-1 Knapsack Problem
- Longest Repeating Subsequence
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Find if a string is interleaved of two other strings | DP-33
- Longest Common Substring | DP-29
- Length of the longest substring without repeating characters