VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-repeating-and-non-overlapping-substring/

⇱ Longest repeating and non-overlapping substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest repeating and non-overlapping substring

Last Updated : 16 Nov, 2024

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.

Using Brute Force Method - O(n^3) Time and O(n) Space

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.


Output
geeks

Using Top-Down DP (Memoization) - O(n^2) Time and O(n^2) Space

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:

  • To avoid overlapping we have to ensure that the length of suffix is less than (j-i) at any instant. 
  • The maximum value of suffix(i, j) provides the length of the longest repeating substring and the substring itself can be found using the length and the starting index of the common suffix.
  • suffix(i, j) stores the length of the longest common suffix between indices i and j, ensuring it doesn’t exceed j - i - 1 to avoid overlap.

Output
geeks

Using Bottom-Up DP (Tabulation) - O(n^2) Time and O(n^2) Space

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.


Output
geeks

Using Space Optimized DP – O(n^2) Time and O(n) Space

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.


Output
geeks

Related articles: 

Comment
Article Tags:
Article Tags: