![]() |
VOOZH | about |
Given a string s, the task is to find the longest repeating non-overlapping substring in it. In other words, find 2 identical substrings of maximum length which do not overlap. Return -1 if no such string exists.
Note: Multiple Answers are possible but we have to return the substring whose first occurrence is earlier.
Examples:
Input: s = "acdcdacdc"
Output: "acdc"
Explanation: The string "acdc" is the longest Substring of s which is repeating but not overlapping.Input: s = "geeksforgeeks"
Output: "geeks"
Explanation: The string "geeks" is the longest subString of s which is repeating but not overlapping.
Table of Content
The idea is to generate all the possible substrings and check if the substring exists in the remaining string. If substring exists and its length is greater than answer substring, then set answer to current substring.
geeks
The approach is to compute the longest repeating suffix for all prefix pairs in the string s. For indices i and j, if s[i] == s[j], then recursively compute suffix(i+1, j+1) and set suffix(i, j) as min(suffix(i+1, j+1) + 1, j - i - 1) to prevent overlap. If the characters do not match, set suffix(i, j) = 0.
Note:
geeks
The idea is to create a 2D matrix of size (n+1)*(n+1) and calculate the longest repeating suffixes for all index pairs (i, j) iteratively. We start from the end of the string and work backwards to fill the table. For each (i, j), if s[i] == s[j], we set suffix[i][j] to min(suffix[i+1][j+1]+1, j-i-1) to avoid overlap; otherwise, suffix[i][j] = 0.
geeks
The idea is to use a single 1D array instead of a 2D matrix by keeping track of only the "next row" values required to compute suffix[i][j]. Since each value suffix[i][j] depends only on suffix[i+1][j+1] in the row below, we can maintain the previous row's values in a 1D array and update them iteratively for each row.
geeks
Related articles: