18. Longest Repeating Subsequence
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To find the length of the longest repeating subsequence in a given string, I used a recursive approach with memoization.
In function maxSub
that takes the starting indices i
and j
, the length of the string n
, the string s
, and a memoization table dp
.
If i
or j
reaches the end of the string n
, return 0.
If the subproblem has already been computed and stored in dp[i][j]
, return the result from dp
.
If the characters at indices i
and j
are equal and i
is not equal to j
, then the current characters contribute to the length of the repeating subsequence. Recursively call maxSub
with i + 1
and j + 1
to find the length of the next repeating subsequence.
If the characters at indices i
and j
are not equal, then one of them cannot be part of the repeating subsequence. Recursively call maxSub
with either i
and j + 1
or i + 1
and j
, and take the maximum of the two results.
Store the computed result in dp[i][j]
.
Time Complexity: O(n^2)
due to the nested recursive calls and the memoization table.
Auxiliary Space Complexity: O(n^2)
as we use a memoization table of size n * n.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the repository.