Skip to content

Commit 9ee1489

Browse files
authored
Create LongestRepeatedSubsequenceProblem.java
1 parent 039bb01 commit 9ee1489

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
https://www.techiedelight.com/longest-repeated-subsequence-problem/
3+
4+
The problem is a modification of Longest Common Subsequence Problem. Here, we take both the strings to be the same and then find the Longest Common Subsequence.
5+
6+
The Recurrence is almost the same as LCS -
7+
LRS[i][j] = 0 if i = 0 || j = 0
8+
= LRS[i-1][j-1] if (i != j) && s[i] == s[j]
9+
= max(LRS[i-1][j], LRS[i][j-1]) if s[i] != s[j]
10+
i and j can not have the same index as they represent the indixes of the same string.
11+
12+
Normal Recursion would require exponential time and in worst case - NONE OF THE CHARACTERS REPEAT - time complexity turns out to be O(2^n). Each call further makes two other calls.
13+
14+
*/
15+
16+
17+
//Memoized Recursion
18+
19+
public int LRSlen(String s, int i, int j, HashMap<String, Integer> map){
20+
if(i==0 || j==0) return 0; //nothing to check of repetition - we have exhausted the string
21+
22+
String key = i+"|"+j;
23+
24+
if(!map.containsKey(key)){
25+
if(i!=j && s.charAt(i-1) == s.charAt(j-1)){
26+
map.put(key, LRSlen(s, i-1, j-1, map) + 1);
27+
}
28+
else{
29+
map.put(key, Math.max(LRSlen(s, i-1, j, map), LRSlen(s, i, j-1, map)));
30+
}
31+
}
32+
return map.get(key);
33+
}
34+
//Time & Space Complexity - O(n^2)
35+
36+
37+
//Bottom Up DP
38+
39+
public int LRSlen(String s){
40+
int n = s.length();
41+
42+
//len[i][j] indicates the length of the LRS of s[0...i-1] and s[0...j-1]
43+
int len[][] = new int[n+1][n+1];
44+
45+
for(int i=1 ; i < n ; i++){
46+
for(int j=1 ; j < n ; j++){
47+
if( i!=j && s.charAt(i-1) == s.charAt(j-1) ){
48+
len[i][j] = len[i-1][j-1] + 1;
49+
}
50+
else len[i][j] = Math.max(len[i][j-1], len[i-1][j]);
51+
}
52+
}
53+
54+
return len[n][n];
55+
}
56+
57+
/*
58+
Time Complexity - O(n^2)
59+
Space Complexity - O(n^2) --> can be further optimized to O(n) [we only require the values from the previous rows]
60+
*/
61+
62+
//Print the LRS --> Assuming we already have the 2D len[][] array with us
63+
64+
public String printLRS(String s, int i, int j, int len[][]){
65+
if(i==0 || j==0) return "";
66+
67+
if(i!=j && s.charAt(i-1) == s.charAt(j-1)){
68+
return printLRS(s, i-1, j-1, len) + s.charAt(i-1);
69+
}
70+
else{
71+
if(len[i-1][j] > len[i][j-1]){
72+
return printLRS(s, i-1, j, len);
73+
}
74+
else{
75+
return printLRS(s, i, j-1, len);
76+
}
77+
}
78+
79+
}

0 commit comments

Comments
 (0)