Here’s the question link on GFG: Longest Repeating Subsequence:
https://www.geeksforgeeks.org/problems/longest-repeating-subsequence2004/1
Contents
Brute Force: Recursion
Think of this as finding the Longest Common Subsequence (LCS) of the string with itself.
We compare the string with itself using two pointers, i and j.
There are two possibilities:
- If the characters match and
i != j, we can include that character and move both pointers. - Otherwise, we try skipping a character from either side and take the maximum result.
If either pointer reaches the beginning, return 0.
class Solution {
public:
int solve(int i, int j, string &s) {
if(i == 0 || j == 0)
return 0;
if(s[i - 1] == s[j - 1] && i != j)
return 1 + solve(i - 1, j - 1, s);
return max(solve(i - 1, j, s),
solve(i, j - 1, s));
}
int longestRepSubseq(string &s) {
int n = s.size();
return solve(n, n, s);
}
};
Optimal: Dynamic Programming (LCS) — O(n²)
Here’s the interesting part: this problem is almost exactly the Longest Common Subsequence (LCS) problem.
Normally, in LCS, we compare two strings and find their longest common subsequence.
Here, we compare the same string with itself!
The only additional condition is that the two matching characters must come from different indices.
Step 1: Create a DP table
vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
dp[i][j] stores the length of the longest repeating subsequence considering the first i and j characters.
Step 2: Fill the DP table
We have two cases:
Case 1: Characters match and indices are different.
if(s[i - 1] == s[j - 1] && i != j)
dp[i][j] = 1 + dp[i - 1][j - 1];
We include the matching character and add 1 to the previous diagonal result.
Case 2: Characters don’t match OR indices are the same.
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
We skip a character from either side and take whichever gives us the longer subsequence.
Finally, dp[n][n] contains our answer.
class Solution {
public:
int longestRepSubseq(string &s) {
int n = s.size();
vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(s[i - 1] == s[j - 1] && i != j) {
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][n];
}
};![Longest Repeating Subsequence Optimal Solution [dp]](https://python-hub.com/wp-content/uploads/2026/11/image-34.png)