Given a string, find the length of the longest repeating subsequence, such that the two subsequences don’t have same string character at the same position, i.e. any ith character in the two subsequences shouldn’t have the same index in the original string.
Examples:
Input: str = "abc"
Output: 0
There is no repeating subsequence
Input: str = "aab"
Output: 1
The two subsequence are 'a'(first) and 'a'(second).
Note that 'b' cannot be considered as part of subsequence
as it would be at same index in both.
Input: str = "aabb"
Output: 2
Input: str = "axxxy"
Output: 2
Method 1: This problem is just the modification of Longest Common Subsequence problem. The idea is to find the LCS(str, str) where, str is the input string with the restriction that when both the characters are same, they shouldn’t be on the same index in the two strings.
Initialize the input string, which is to be checked.
Initialize the length of string to the variable.
create a DP table using 2D matrix and set each element to 0.
Fill the table if the characters are same and indexes are different.
Return the values inside the table
Print the String.
Below is the implementation of the idea.
C++
// C++ program to find the longest repeating
// subsequence
#include <iostream>
#include <string>
usingnamespacestd;
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
intfindLongestRepeatingSubSeq(string str)
{
intn = str.length();
// Create and initialize DP table
intdp[n+1][n+1];
for(inti=0; i<=n; i++)
for(intj=0; j<=n; j++)
dp[i][j] = 0;
// Fill dp table (similar to LCS loops)
for(inti=1; i<=n; i++)
{
for(intj=1; j<=n; j++)
{
// If characters match and indexes are
// not same
if(str[i-1] == str[j-1] && i != j)
dp[i][j] = 1 + dp[i-1][j-1];
// If characters do not match
else
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
returndp[n][n];
}
// Driver Program
intmain()
{
string str = "aabb";
cout << "The length of the largest subsequence that"
" repeats itself is : "
<< findLongestRepeatingSubSeq(str);
return0;
}
Java
// Java program to find the longest
// repeating subsequence
importjava.io.*;
importjava.util.*;
classLRS
{
// Function to find the longest repeating subsequence
staticintfindLongestRepeatingSubSeq(String str)
{
intn = str.length();
// Create and initialize DP table
int[][] dp = newint[n+1][n+1];
// Fill dp table (similar to LCS loops)
for(inti=1; i<=n; i++)
{
for(intj=1; j<=n; j++)
{
// If characters match and indexes are not same
if(str.charAt(i-1) == str.charAt(j-1) && i!=j)
dp[i][j] = 1+ dp[i-1][j-1];
// If characters do not match
else
dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
}
}
returndp[n][n];
}
// driver program to check above function
publicstaticvoidmain (String[] args)
{
String str = "aabb";
System.out.println("The length of the largest subsequence that"
+" repeats itself is : "+findLongestRepeatingSubSeq(str));
}
}
// This code is contributed by Pramod Kumar
Python3
# Python 3 program to find the longest repeating
# subsequence
# This function mainly returns LCS(str, str)
# with a condition that same characters at
# same index are not considered.
deffindLongestRepeatingSubSeq( str):
n =len(str)
# Create and initialize DP table
dp=[[0fori inrange(n+1)] forj inrange(n+1)]
# Fill dp table (similar to LCS loops)
fori inrange(1,n+1):
forj inrange(1,n+1):
# If characters match and indexes are
# not same
if(str[i-1] ==str[j-1] andi !=j):
dp[i][j] =1+dp[i-1][j-1]
# If characters do not match
else:
dp[i][j] =max(dp[i][j-1], dp[i-1][j])
returndp[n][n]
# Driver Program
if__name__=='__main__':
str="aabb"
print("The length of the largest subsequence that repeats itself is : "
,findLongestRepeatingSubSeq(str))
# this code is contributed by ash264
C#
// C# program to find the longest repeating
// subsequence
usingSystem;
classGFG {
// Function to find the longest repeating
// subsequence
staticintfindLongestRepeatingSubSeq(stringstr)
{
intn = str.Length;
// Create and initialize DP table
int[,]dp = newint[n+1,n+1];
// Fill dp table (similar to LCS loops)
for(inti = 1; i <= n; i++)
{
for(intj = 1; j <= n; j++)
{
// If characters match and indexes
// are not same
if(str[i-1] == str[j-1] && i != j)
dp[i,j] = 1 + dp[i-1,j-1];
// If characters do not match
else
dp[i,j] = Math.Max(dp[i,j-1],
dp[i-1,j]);
}
}
returndp[n,n];
}
// driver program to check above function
publicstaticvoidMain ()
{
stringstr = "aabb";
Console.Write("The length of the largest "
+ "subsequence that repeats itself is : "
+ findLongestRepeatingSubSeq(str));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find the
// longest repeating subsequence
// This function mainly returns
// LCS(str, str) with a condition
// that same characters at same
// index are not considered.
functionfindLongestRepeatingSubSeq($str)
{
$n= strlen($str);
// Create and initialize
// DP table
$dp= array(array());
for($i= 0; $i<= $n; $i++)
for($j= 0; $j<= $n; $j++)
$dp[$i][$j] = 0;
// Fill dp table
// (similar to LCS loops)
for($i= 1; $i<= $n; $i++)
{
for($j= 1; $j<= $n; $j++)
{
// If characters match and
// indexes are not same
if($str[$i- 1] == $str[$j- 1] &&
$i!= $j)
$dp[$i][$j] = 1 + $dp[$i- 1][$j- 1];
// If characters
// do not match
else
$dp[$i][$j] = max($dp[$i][$j- 1],
$dp[$i- 1][$j]);
}
}
return$dp[$n][$n];
}
// Driver Code
$str= "aabb";
echo"The length of the largest ".
"subsequence that repeats itself is : ",
findLongestRepeatingSubSeq($str);
// This code is contributed
// by shiv_bhakt.
?>
Javascript
<script>
// Javascript program to find the longest repeating
// subsequence
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
functionfindLongestRepeatingSubSeq(str)
{
varn = str.length;
// Create and initialize DP table
vardp = newArray(n + 1);
for(vari=0; i<=n; i++)
{
dp[i] = newArray(n + 1);
for(varj=0; j<=n; j++)
{
dp[i][j] = 0;
}
}
// Fill dp table (similar to LCS loops)
for(vari=1; i<=n; i++)
{
for(varj=1; j<=n; j++)
{
// If characters match and indexes are
// not same
if((str[i-1] == str[j-1]) && (i != j))
dp[i][j] = 1 + dp[i-1][j-1];
// If characters do not match
else
dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
}
}
returndp[n][n];
}
// Driver Code
varstr = "aabb";
document.write("The length of the largest subsequence that repeats itself is : "+ findLongestRepeatingSubSeq(str));
</script>
Output
The length of the largest subsequence that repeats itself is : 2
dp[i][j] = Math.max(lrs(s1, i, j + 1, dp), lrs(s1, i + 1, j, dp));
}
}
returndp[i][j];
}
// Driver code
publicstaticvoidmain (String[] args)
{
String s1 = "aabb";
StringBuilder input1 = newStringBuilder();
// append a string into StringBuilder input1
input1.append(s1);
// reverse StringBuilder input1
input1.reverse();
int[][] dp = newint[1000][1000];
for(int[] row : dp)
{
Arrays.fill(row, -1);
}
System.out.println("LENGTH OF LONGEST REPEATING SUBSEQUENCE IS :"+
lrs(input1, 0, 0, dp));
}
}
// This code is contributed by rag2127.
Python3
# Python 3 program to find the longest repeating
# subsequence Length
# This function mainly returns LRS(str, str,i,j,dp)
# with a condition that same characters at
# same index are not considered.
deflrs(s1, i, j, dp):
# return if we have reached the
#end of either string
ifi >=len(s1) orj >=len(s1):
return0
ifdp[i][j] !=-1:
returndp[i][j]
# while dp[i][j] is not computed earlier
ifdp[i][j] ==-1:
# if characters at index m and n matches
# and index is different
# Index should not match
ifs1[i] ==s1[j] andi !=j:
dp[i][j] =1+lrs(s1, i+1, j+1, dp)
# else if characters at index m and n don't match
else:
dp[i][j] =max(lrs(s1, i, j+1, dp),
lrs(s1, i+1, j, dp))
# return answer
returndp[i][j]
# Driver Code
if__name__ =="__main__":
s1 ="aabb"
# Reversing the same string
s2 =s1[::-1]
dp =[[-1fori inrange(1000)] forj inrange(1000)]
print("LENGTH OF LONGEST REPEATING SUBSEQUENCE IS :",
lrs(s1, 0, 0, dp))
# this code is contributed by saikumar kudikala
C#
usingSystem;
publicclassGFG{
staticintlrs(strings1, inti, intj, int[,] dp)
{
if(i >= s1.Length || j >= s1.Length)
{
return0;
}
if(dp[i, j] != -1)
{
returndp[i, j];
}
if(dp[i, j] == -1)
{
if(s1[i] == s1[j] && i != j)
{
dp[i, j] = 1 + lrs(s1, i + 1, j + 1, dp);
}
else
{
dp[i, j] = Math.Max(lrs(s1, i, j + 1, dp), lrs(s1, i + 1, j, dp));
}
}
returndp[i, j];
}
// Driver code
staticpublicvoidMain (){
strings1 = "aabb";
char[] chars = s1.ToCharArray();
Array.Reverse(chars);
s1= newString(chars);
int[,] dp = newint[1000,1000];
for(inti = 0; i < 1000; i++)
{
for(intj = 0; j < 1000; j++)
{
dp[i, j] = -1;
}
}
Console.WriteLine("LENGTH OF LONGEST REPEATING SUBSEQUENCE IS :"+
lrs(s1, 0, 0, dp));
}
}
// This code is contributed by avanitrachhadiya2155
Javascript
<script>
functionlrs(s1, i, j, dp)
{
if(i >= s1.length || j >= s1.length)
{
return0;
}
if(dp[i][j] != -1)
{
returndp[i][j];
}
if(dp[i][j] == -1)
{
if(s1[i] == s1[j] && i != j)
{
dp[i][j] = 1 + lrs(s1, i + 1,
j + 1, dp);
}
else
{
dp[i][j] = Math.max(lrs(s1, i, j + 1, dp),
lrs(s1, i + 1, j, dp));
}
}
returndp[i][j];
}
// Driver code
let s1 = "aabb";
// Append a string into StringBuilder input1
let input1 = s1.split("");
// Reverse StringBuilder input1
input1.reverse();
let dp = newArray(1000);
for(let i = 0; i < 1000; i++)
{
dp[i] = newArray(1000);
for(let j = 0; j < 1000; j++)
{
dp[i][j] = -1;
}
}
document.write("LENGTH OF LONGEST REPEATING "+
"SUBSEQUENCE IS :"+
lrs(input1, 0, 0, dp));
// This code is contributed by unknown2108
</script>
Output
LENGTH OF LONGEST REPEATING SUBSEQUENCE IS : 2
Time Complexity: O(n2) Auxiliary Space: O(n2)
Method 4: If we look closely at solution 1, we can analyze that we are using only the previous column and element just above the current element.
C++
#include <bits/stdc++.h>
usingnamespacestd;
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
intfindLongestRepeatingSubSeq(string str)
{
intn = str.length();
// Create and initialize DP table
intdp[n+1] = {0};
// Fill dp table (similar to LCS loops)
for(inti=1; i<=n; i++)
{
intnew_a[n+1] = {0};
for(intj=1; j<=n; j++)
{
// If characters match and indexes are
// not same
if(str[i-1] == str[j-1] && i != j)
{
new_a[j] = 1 + dp[j-1];
}
// If characters do not match
else
{
new_a[j] = max(dp[j], new_a[j-1]);
}
}
for(intj=0; j<=n; j++)
dp[j] = new_a[j];
}
returndp[n];
}
// Driver Program
intmain()
{
string str = "aabb";
cout << "The length of the largest subsequence that"
<< " repeats itself is : "
<< findLongestRepeatingSubSeq(str);
return0;
}
Java
// Java program to find Longest Repeating
// Subsequence
importjava.util.*;
classGFG {
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
staticintfindLongestRepeatingSubSeq(String str)
{
intn = str.length();
// Create and initialize DP table
int[][] dp = newint[n + 1][n + 1];
// Fill dp table (similar to LCS loops)
for(inti = 1; i <= n; i++)
{
for(intj = 1; j <= n; j++)
{
// If characters match and indexes are
// not same
if(str.charAt(i - 1) == str.charAt(j - 1)
&& i != j)
{
dp[i][j] = 1+ dp[i - 1][j - 1];
}
// If characters do not match
else
{
dp[i][j] = Math.max(dp[i][j - 1],
dp[i - 1][j]);
}
}
}
returndp[n][n];
}
// Driver Program
publicstaticvoidmain(String[] args)
{
String str = "aabb";
System.out.println("The length of the largest subsequence that "
+ "repeats itself is : "+
findLongestRepeatingSubSeq(str));
}
}
Python3
# Python 3 program to find the longest repeating
# subsequence
# This function mainly returns LCS(str, str)
# with a condition that same characters at
# same index are not considered.
deffindLongestRepeatingSubSeq(str):
n =len(str)
# Create and initialize DP table
dp =[0fori inrange(n +1)]
# Fill dp table (similar to LCS loops)
fori inrange(1, n +1):
new_a =[0]
forj inrange(1, n +1):
# If characters match and indexes are
# not same
ifstr[i -1] ==str[j -1] andi !=j:
new_a.append(1+dp[j -1])
# If characters do not match
else:
new_a.append(max(dp[j], new_a[-1]))
dp =new_a[:]
returndp[-1]
# Driver Program
if__name__ =='__main__':
str="aabb"
print("The length of the largest subsequence that repeats itself is : ", findLongestRepeatingSubSeq(str))
# this code is contributed by ash264
C#
usingSystem;
namespacefindLongestRepeatingSubSeq {
classGFG {
staticintfindLongestRepeatingSubSeq(stringstr)
{
intn = str.Length;
// Create and initialize DP table
int[] dp = newint[n + 1];
// Fill dp table (similar to LCS loops)
for(inti = 1; i <= n; i++) {
int[] new_a = newint[n + 1];
for(intj = 1; j <= n; j++) {
// If characters match and indexes are
// not same
if(str[i - 1] == str[j - 1] && i != j) {
new_a[j] = 1 + dp[j - 1];
}
// If characters do not match
else{
new_a[j]
= Math.Max(dp[j], new_a[j - 1]);
}
}
for(intj = 0; j <= n; j++)
dp[j] = new_a[j];
}
returndp[n];
}
// Driver Program
staticvoidMain(string[] args)
{
stringstr = "aabb";
Console.WriteLine(
"The length of the largest subsequence that"
+ " repeats itself is : "
+ findLongestRepeatingSubSeq(str));
}
}
}
// This code is contributed by Susobhan Akhuli
Javascript
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
functionfindLongestRepeatingSubSeq( str)
{
let n = str.length;
// Create and initialize DP table
let dp=newArray(n+1).fill(0);
// Fill dp table (similar to LCS loops)
for(let i=1; i<=n; i++)
{
let new_a=newArray(n+1).fill(0);
for(let j=1; j<=n; j++)
{
// If characters match and indexes are
// not same
if(str[i-1] == str[j-1] && i != j)
{
new_a[j] = 1 + dp[j-1];
}
// If characters do not match
else
{
new_a[j] = Math.max(dp[j], new_a[j-1]);
}
}
for(let j=0; j<=n; j++)
dp[j] = new_a[j];
}
returndp[n];
}
// Driver Program
let str = "aabb";
console.log("The length of the largest subsequence that"
+ " repeats itself is : "+ findLongestRepeatingSubSeq(str));
Output
The length of the largest subsequence that repeats itself is : 2
Time Complexity: O(n2) Auxiliary Space: O(n)
This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!