Longest repeating and non-overlapping substring

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
class Solution {
    public String longestRepeatedSubstring(String str) {
        int n = str.length();
        // dp[i][j] -> Length of longest repeating substring ending at i and jth indices
        int dp[][] = new int[n + 1][n + 1];
        int res_length = 0;
        int index = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                // If the characters at ith and jth indices are same
                // Then we need to check that there should be no overlap
                // This can be done by just checking is the distance
                // between i & j > the length of previous matching substring(dp[i-1][j-1])
                if (str.charAt(i - 1) == str.charAt(j - 1) && dp[i - 1][j - 1] < (j - i)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;

                    if (dp[i][j] > res_length) {
                        res_length = dp[i][j];
                        index = i;
                    }
                }
                // Default dp[i][j]->0
            }
        }
        StringBuilder res = new StringBuilder();
        while (res_length > 0)
            res.append(str.charAt(i--));

        return res.reverse().toString();
    }
}

Last updated