Skip to content

Commit 12935c2

Browse files
caglarekerÇağlar Eker
andauthored
Add Longest Repeated Substring algorithm (#7286)
* Add Longest Repeated Substring algorithm Implement LongestRepeatedSubstring in the strings package using the existing SuffixArray and Kasai's algorithm for LCP array construction. Includes parameterized unit tests covering typical and edge cases. * style: reformat test file per clang-format and add coverage test --------- Co-authored-by: Çağlar Eker <eker.caglar@hepsiburada.com>
1 parent 109df1f commit 12935c2

File tree

2 files changed

+116
-0
lines changed

2 files changed

+116
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.thealgorithms.strings;
2+
3+
/**
4+
* Finds the longest substring that occurs at least twice in a given string.
5+
*
6+
* <p>Uses the suffix array (via {@link SuffixArray}) and Kasai's algorithm
7+
* to build the LCP (Longest Common Prefix) array, then returns the substring
8+
* corresponding to the maximum LCP value.</p>
9+
*
10+
* <p>Time complexity: O(n log² n) for suffix array construction + O(n) for LCP.</p>
11+
*
12+
* @see <a href="https://en.wikipedia.org/wiki/Longest_repeated_substring_problem">Longest repeated substring problem</a>
13+
* @see SuffixArray
14+
*/
15+
public final class LongestRepeatedSubstring {
16+
17+
private LongestRepeatedSubstring() {
18+
}
19+
20+
/**
21+
* Returns the longest substring that appears at least twice in the given text.
22+
*
23+
* @param text the input string
24+
* @return the longest repeated substring, or an empty string if none exists
25+
*/
26+
public static String longestRepeatedSubstring(String text) {
27+
if (text == null || text.length() <= 1) {
28+
return "";
29+
}
30+
31+
final int[] suffixArray = SuffixArray.buildSuffixArray(text);
32+
final int[] lcp = buildLcpArray(text, suffixArray);
33+
34+
int maxLen = 0;
35+
int maxIdx = 0;
36+
for (int i = 0; i < lcp.length; i++) {
37+
if (lcp[i] > maxLen) {
38+
maxLen = lcp[i];
39+
maxIdx = suffixArray[i + 1];
40+
}
41+
}
42+
43+
return text.substring(maxIdx, maxIdx + maxLen);
44+
}
45+
46+
/**
47+
* Builds the LCP (Longest Common Prefix) array using Kasai's algorithm.
48+
*
49+
* <p>LCP[i] is the length of the longest common prefix between the suffixes
50+
* at positions suffixArray[i] and suffixArray[i+1] in sorted order.</p>
51+
*
52+
* @param text the original string
53+
* @param suffixArray the suffix array of the string
54+
* @return the LCP array of length n-1
55+
*/
56+
static int[] buildLcpArray(String text, int[] suffixArray) {
57+
final int n = text.length();
58+
final int[] rank = new int[n];
59+
final int[] lcp = new int[n - 1];
60+
61+
for (int i = 0; i < n; i++) {
62+
rank[suffixArray[i]] = i;
63+
}
64+
65+
int k = 0;
66+
for (int i = 0; i < n; i++) {
67+
if (rank[i] == n - 1) {
68+
k = 0;
69+
continue;
70+
}
71+
final int j = suffixArray[rank[i] + 1];
72+
while (i + k < n && j + k < n && text.charAt(i + k) == text.charAt(j + k)) {
73+
k++;
74+
}
75+
lcp[rank[i]] = k;
76+
if (k > 0) {
77+
k--;
78+
}
79+
}
80+
81+
return lcp;
82+
}
83+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.thealgorithms.strings;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
6+
import java.util.stream.Stream;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.Arguments;
9+
import org.junit.jupiter.params.provider.MethodSource;
10+
11+
class LongestRepeatedSubstringTest {
12+
13+
@ParameterizedTest(name = "\"{0}\" -> \"{1}\"")
14+
@MethodSource("provideTestCases")
15+
void testLongestRepeatedSubstring(String input, String expected) {
16+
assertEquals(expected, LongestRepeatedSubstring.longestRepeatedSubstring(input));
17+
}
18+
19+
private static Stream<Arguments> provideTestCases() {
20+
return Stream.of(Arguments.of("banana", "ana"), Arguments.of("abcabc", "abc"), Arguments.of("aaaa", "aaa"), Arguments.of("abcd", ""), Arguments.of("a", ""), Arguments.of("", ""), Arguments.of(null, ""), Arguments.of("aab", "a"), Arguments.of("aa", "a"), Arguments.of("mississippi", "issi"));
21+
}
22+
23+
@ParameterizedTest(name = "\"{0}\" -> LCP={1}")
24+
@MethodSource("provideLcpTestCases")
25+
void testBuildLcpArray(String input, int[] expectedLcp) {
26+
int[] suffixArray = SuffixArray.buildSuffixArray(input);
27+
assertArrayEquals(expectedLcp, LongestRepeatedSubstring.buildLcpArray(input, suffixArray));
28+
}
29+
30+
private static Stream<Arguments> provideLcpTestCases() {
31+
return Stream.of(Arguments.of("banana", new int[] {1, 3, 0, 0, 2}), Arguments.of("ab", new int[] {0}));
32+
}
33+
}

0 commit comments

Comments
 (0)