(Translated by https://www.hiragana.jp/)
Longest Repeating Subsequence - GeeksforGeeks
Open In App

Longest Repeating Subsequence

Last Updated : 17 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
48.54%
1.3L

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. 

longest-repeating-subsequence

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
Recommended Practice

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>
using namespace std;
 
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
int findLongestRepeatingSubSeq(string str)
{
    int n = str.length();
 
    // Create and initialize DP table
    int dp[n+1][n+1];
    for (int i=0; i<=n; i++)
        for (int j=0; j<=n; j++)
            dp[i][j] = 0;
 
    // Fill dp table (similar to LCS loops)
    for (int i=1; i<=n; i++)
    {
        for (int 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 Program
int main()
{
    string str = "aabb";
    cout << "The length of the largest subsequence that"
            " repeats itself is : "
        << findLongestRepeatingSubSeq(str);
    return 0;
}


Java




// Java program to find the longest
// repeating subsequence
import java.io.*;
import java.util.*;
 
class LRS
{
    // Function to find the longest repeating subsequence
    static int findLongestRepeatingSubSeq(String str)
    {
        int n = str.length();
  
        // Create and initialize DP table
        int[][] dp = new int[n+1][n+1];
  
        // Fill dp table (similar to LCS loops)
        for (int i=1; i<=n; i++)
        {
            for (int j=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]);
            }
        }
        return dp[n][n];
    }
     
    // driver program to check above function
    public static void main (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.
def findLongestRepeatingSubSeq( str):
 
    n = len(str)
 
    # Create and initialize DP table
    dp=[[0 for i in range(n+1)] for j in range(n+1)]
 
    # Fill dp table (similar to LCS loops)
    for i in range(1,n+1):
        for j in range(1,n+1):
            # If characters match and indexes are
            # not same
            if (str[i-1] == str[j-1] and 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 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
using System;
 
class GFG {
     
    // Function to find the longest repeating
    // subsequence
    static int findLongestRepeatingSubSeq(string str)
    {
        int n = str.Length;
 
        // Create and initialize DP table
        int [,]dp = new int[n+1,n+1];
 
        // Fill dp table (similar to LCS loops)
        for (int i = 1; i <= n; i++)
        {
            for (int 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] = Math.Max(dp[i,j-1],
                                       dp[i-1,j]);
            }
        }
        return dp[n,n];
    }
     
    // driver program to check above function
    public static void Main ()
    {
        string str = "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.
function findLongestRepeatingSubSeq($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.
    function findLongestRepeatingSubSeq(str)
    {
        var n = str.length;
      
        // Create and initialize DP table
        var dp = new Array(n + 1);
         
        for (var i=0; i<=n; i++)
        {
            dp[i] = new Array(n + 1);
            for (var j=0; j<=n; j++)
            {
                dp[i][j] = 0;
            }
        }
             
        // Fill dp table (similar to LCS loops)
        for (var i=1; i<=n; i++)
        {
            for (var 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] = Math.max(dp[i][j-1], dp[i-1][j]);
            }
        }
        return dp[n][n];
    }
    // Driver Code
     
    var str = "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

Time Complexity: O(n2)
Auxiliary Space: O(n2)

Method 2: (Using recursion)

C++




// C++ program to find the longest repeating
// subsequence using recursion
#include <bits/stdc++.h>
using namespace std;
 
int dp[1000][1000];
 
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
 
int findLongestRepeatingSubSeq(string X, int m, int n)
{
     
    if(dp[m][n]!=-1)
    return dp[m][n];
     
    // return if we have reached the end of either string
    if (m == 0 || n == 0)
        return dp[m][n] = 0;
 
    // if characters at index m and n matches
    // and index is different
    if (X[m - 1] == X[n - 1] && m != n)
        return dp[m][n] = findLongestRepeatingSubSeq(X,
                            m - 1, n - 1) + 1;
 
    // else if characters at index m and n don't match
    return dp[m][n] = max (findLongestRepeatingSubSeq(X, m, n - 1),
                           findLongestRepeatingSubSeq(X, m - 1, n));
}
 
// Longest Repeated Subsequence Problem
int main()
{
    string str = "aabb";
    int m = str.length();
 
memset(dp,-1,sizeof(dp));
cout << "The length of the largest subsequence that"
            " repeats itself is : "
        << findLongestRepeatingSubSeq(str,m,m);
 
    return 0;
// this code is contributed by Kushdeep Mittal
}


Java




import java.util.Arrays;
 
// Java program to find the longest repeating
// subsequence using recursion
public class GFG {
 
    static int dp[][] = new int[1000][1000];
 
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
    static int findLongestRepeatingSubSeq(char X[], int m, int n) {
 
        if (dp[m][n] != -1) {
            return dp[m][n];
        }
 
        // return if we have reached the end of either string
        if (m == 0 || n == 0) {
            return dp[m][n] = 0;
        }
 
        // if characters at index m and n matches
        // and index is different
        if (X[m - 1] == X[n - 1] && m != n) {
            return dp[m][n] = findLongestRepeatingSubSeq(X,
                    m - 1, n - 1) + 1;
        }
 
        // else if characters at index m and n don't match
        return dp[m][n] = Math.max(findLongestRepeatingSubSeq(X, m, n - 1),
                findLongestRepeatingSubSeq(X, m - 1, n));
    }
 
// Longest Repeated Subsequence Problem
    static public void main(String[] args) {
        String str = "aabb";
        int m = str.length();
        for (int[] row : dp) {
            Arrays.fill(row, -1);
        }
        System.out.println("The length of the largest subsequence that"
                + " repeats itself is : "
                + findLongestRepeatingSubSeq(str.toCharArray(), m, m));
 
    }
}
 
// This code is contributed by 29AjayKumar


Python3




# Python 3 program to find the longest repeating
# subsequence using recursion
 
dp = [[0 for i in range(1000)] for j in range(1000)]
 
# This function mainly returns LCS(str, str)
# with a condition that same characters at
# same index are not considered.
 
def findLongestRepeatingSubSeq( X, m, n):
     
    if(dp[m][n]!=-1):
        return dp[m][n]
     
    # return if we have reached the end of either string
    if (m == 0 or n == 0):
        dp[m][n] = 0
        return dp[m][n]
 
    # if characters at index m and n matches
    # and index is different
    if (X[m - 1] == X[n - 1] and m != n):
        dp[m][n] = findLongestRepeatingSubSeq(X,
                            m - 1, n - 1) + 1
         
        return dp[m][n]
 
    # else if characters at index m and n don't match
    dp[m][n] = max (findLongestRepeatingSubSeq(X, m, n - 1),
                        findLongestRepeatingSubSeq(X, m - 1, n))
    return dp[m][n]
 
# Longest Repeated Subsequence Problem
if __name__ == "__main__":
    str = "aabb"
    m = len(str)
 
dp =[[-1 for i in range(1000)] for j in range(1000)]
print( "The length of the largest subsequence that"
            " repeats itself is : "
        , findLongestRepeatingSubSeq(str,m,m))
         
# this code is contributed by
# ChitraNayal


C#




//C# program to find the longest repeating
// subsequence using recursion
using System;
public class GFG {
 
    static int [,]dp = new int[1000,1000];
 
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
    static int findLongestRepeatingSubSeq(char []X, int m, int n) {
 
        if (dp[m,n] != -1) {
            return dp[m,n];
        }
 
        // return if we have reached the end of either string
        if (m == 0 || n == 0) {
            return dp[m,n] = 0;
        }
 
        // if characters at index m and n matches
        // and index is different
        if (X[m - 1] == X[n - 1] && m != n) {
            return dp[m,n] = findLongestRepeatingSubSeq(X,
                    m - 1, n - 1) + 1;
        }
 
        // else if characters at index m and n don't match
        return dp[m,n] = Math.Max(findLongestRepeatingSubSeq(X, m, n - 1),
                findLongestRepeatingSubSeq(X, m - 1, n));
    }
 
// Longest Repeated Subsequence Problem
    static public void Main() {
        String str = "aabb";
        int m = str.Length;
        for (int i = 0; i < dp.GetLength(0); i++)
            for (int j = 0; j < dp.GetLength(1); j++)
                dp[i, j] = -1;
        Console.WriteLine("The length of the largest subsequence that"
                + " repeats itself is : "
                + findLongestRepeatingSubSeq(str.ToCharArray(), m, m));
 
    }
}
 
// This code is contributed by 29AjayKumar


PHP




<?php
// PHP program to find the longest repeating
// subsequence using recursion
 
$dp = array_fill(0, 1000, array_fill(0, 1000, -1));
 
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
 
function findLongestRepeatingSubSeq($X, $m, $n)
{
    global $dp;
     
    if($dp[$m][$n] != -1)
    return $dp[$m][$n];
     
    // return if we have reached the end of either string
    if ($m == 0 || $n == 0)
        return $dp[$m][$n] = 0;
 
    // if characters at index m and n matches
    // and index is different
    if ($X[$m - 1] == $X[$n - 1] && $m != $n)
        return $dp[$m][$n] = findLongestRepeatingSubSeq($X,
                            $m - 1, $n - 1) + 1;
 
    // else if characters at index m and n don't match
    return $dp[$m][$n] = max (findLongestRepeatingSubSeq($X, $m, $n - 1),
                        findLongestRepeatingSubSeq($X, $m - 1, $n));
}
 
// Driver code
 
    $str = "aabb";
    $m = strlen($str);
 
    echo "The length of the largest subsequence".
    "that repeats itself is : ".findLongestRepeatingSubSeq($str,$m,$m);
 
 
// this code is contributed by mits
?>


Javascript




<script>
 
let dp=new Array(1000);
 
for(let i=0;i<1000;i++)
{
    dp[i]=new Array(1000);
    for(let j=0;j<1000;j++)
    {
        dp[i][j]=-1;
    }
     
}
 
function findLongestRepeatingSubSeq(X,m,n)
{
        if (dp[m][n] != -1) {
            return dp[m][n];
        }
  
        // return if we have reached the end of either string
        if (m == 0 || n == 0) {
            return dp[m][n] = 0;
        }
  
        // if characters at index m and n matches
        // and index is different
        if (X[m - 1] == X[n - 1] && m != n) {
            return dp[m][n] = findLongestRepeatingSubSeq(X,
                    m - 1, n - 1) + 1;
        }
  
        // else if characters at index m and n don't match
        return dp[m][n] = Math.max(findLongestRepeatingSubSeq(X, m, n - 1),
                findLongestRepeatingSubSeq(X, m - 1, n));
}
 
let str = "aabb";
let m = str.length;
 
document.write("The length of the largest subsequence that"
                   + " repeats itself is : "
                   + findLongestRepeatingSubSeq(str.split(""), m, m));
 
 
// This code is contributed by ab2127
</script>


Output

The length of the largest subsequence that repeats itself is : 2

Time Complexity: O(m*n)
Auxiliary Space: O(m*n)

Method 3:

To find the length of the Longest Repeating Subsequence  dynamic  programming Top-down Approach:

  • Take the input string.
  • Perform the Longest common subsequence where s1[i]==s1[j] and i!=j.
  • Return the length.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
int lrs(string s1,int i,int j, vector<vector<int>>&dp){
 
    // return if we have reached the
    //end of either string
    if(i >= s1.length() || j >= s1.length())
        return 0;
 
    if(dp[i][j] != -1)
        return dp[i][j];
     
    // while dp[i][j] is not computed earlier
    if(dp[i][j] == -1){
     
        // if characters at index m and n matches
        // and index is different
        // Index should not match
        if(s1[i] == s1[j] && i != 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
    return dp[i][j];
}
 
// Driver Code
int main(){
 
string s1 = "aabb";
     
// Reversing the same string
string s2 = s1;
reverse(s2.begin(),s2.end());
vector<vector<int>>dp(1000,vector<int>(1000,-1));
cout<<"LENGTH OF LONGEST REPEATING SUBSEQUENCE IS : "<<lrs(s1, 0, 0, dp);
 
}
 
// This code is contributed by shinjanpatra


Java




import java.lang.*;
import java.io.*;
import java.util.*;
 
class GFG
{   
  static int lrs(StringBuilder s1, int i, int j, int[][] dp)
  {
    if(i >= s1.length() || j >= s1.length())
    {
      return 0;
    }
 
    if(dp[i][j] != -1)
    {
      return dp[i][j];
    }
 
    if(dp[i][j] == -1)
    {
      if(s1.charAt(i) == s1.charAt(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));
      }
    }
    return dp[i][j];
 
  }
 
  // Driver code
  public static void main (String[] args)
  {   
    String s1 = "aabb";  
    StringBuilder input1 = new StringBuilder();
 
    // append a string into StringBuilder input1
    input1.append(s1);
 
    // reverse StringBuilder input1
    input1.reverse();
    int[][] dp = new int[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.
def lrs(s1, i, j, dp):
   
    # return if we have reached the
    #end of either string
    if i >= len(s1) or j >= len(s1):
        return 0
   
    if dp[i][j] != -1:
        return dp[i][j]
       
    # while dp[i][j] is not computed earlier
    if dp[i][j] == -1:
       
        # if characters at index m and n matches
        # and index is different
        # Index should not match
        if s1[i] == s1[j] and i != 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
    return dp[i][j]
 
# Driver Code
if __name__ == "__main__":
    s1 = "aabb"
     
    # Reversing the same string
    s2 = s1[::-1
    dp =[[-1 for i in range(1000)] for j in range(1000)]
    print("LENGTH OF LONGEST REPEATING SUBSEQUENCE IS :",
                                    lrs(s1, 0, 0, dp))
     
# this code is contributed by saikumar kudikala


C#




using System;
 
public class GFG{
 
  static int lrs(string s1, int i, int j, int[,] dp)
  {
    if(i >= s1.Length || j >= s1.Length)
    {
      return 0;
    }
 
    if(dp[i, j] != -1)
    {
      return dp[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));
      }
    }
    return dp[i, j];
 
  }
 
  // Driver code
  static public void Main (){
    string s1 = "aabb";
    char[] chars = s1.ToCharArray();
    Array.Reverse(chars);
    s1= new String(chars);
 
    int[,] dp = new int[1000,1000];
    for(int i = 0; i < 1000; i++)
    {
      for(int j = 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>
 
function lrs(s1, i, j, dp)
{
    if (i >= s1.length || j >= s1.length)
    {
        return 0;
    }
     
    if (dp[i][j] != -1)
    {
        return dp[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));
        }
    }
    return dp[i][j];
}
 
// Driver code
let  s1 = "aabb";
 
// Append a string into StringBuilder input1
let input1 = s1.split("");
 
// Reverse StringBuilder input1
input1.reverse();
let dp = new Array(1000);
for(let i = 0; i < 1000; i++)
{
    dp[i] = new Array(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>
using namespace std;
 
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
int findLongestRepeatingSubSeq(string str)
{
    int n = str.length();
 
    // Create and initialize DP table
    int dp[n+1] = {0};
 
    // Fill dp table (similar to LCS loops)
    for (int i=1; i<=n; i++)
    {
        int new_a[n+1] = {0};
        for (int 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] = max(dp[j], new_a[j-1]);
            }
        }
        for (int j=0; j<=n; j++)
            dp[j] = new_a[j];
    }
    return dp[n];
}
 
// Driver Program
int main()
{
    string str = "aabb";
    cout << "The length of the largest subsequence that"
         << " repeats itself is : "
         << findLongestRepeatingSubSeq(str);
    return 0;
}


Java




// Java program to find Longest Repeating
// Subsequence
import java.util.*;
 
class GFG {
 
  // This function mainly returns LCS(str, str)
  // with a condition that same characters at
  // same index are not considered.
  static int findLongestRepeatingSubSeq(String str)
  {
    int n = str.length();
 
    // Create and initialize DP table
    int[][] dp = new int[n + 1][n + 1];
 
    // Fill dp table (similar to LCS loops)
    for (int i = 1; i <= n; i++)
    {
      for (int j = 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]);
        }
      }
    }
    return dp[n][n];
  }
 
  // Driver Program
  public static void main(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.
def findLongestRepeatingSubSeq(str):
    n = len(str)
 
    # Create and initialize DP table
    dp = [0 for i in range(n + 1)]
 
    # Fill dp table (similar to LCS loops)
    for i in range(1, n + 1):
        new_a = [0]
        for j in range(1, n + 1):
            # If characters match and indexes are
            # not same
            if str[i - 1] == str[j - 1] and i != 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[:]
    return dp[-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#




using System;
 
namespace findLongestRepeatingSubSeq {
class GFG {
    static int findLongestRepeatingSubSeq(string str)
    {
        int n = str.Length;
 
        // Create and initialize DP table
        int[] dp = new int[n + 1];
 
        // Fill dp table (similar to LCS loops)
        for (int i = 1; i <= n; i++) {
            int[] new_a = new int[n + 1];
            for (int 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 (int j = 0; j <= n; j++)
                dp[j] = new_a[j];
        }
        return dp[n];
    }
 
    // Driver Program
    static void Main(string[] args)
    {
        string str = "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.
function findLongestRepeatingSubSeq( str)
{
    let n = str.length;
 
    // Create and initialize DP table
    let dp=new Array(n+1).fill(0);
 
    // Fill dp table (similar to LCS loops)
    for (let i=1; i<=n; i++)
    {
        let new_a=new Array(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];
    }
    return dp[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)



Previous Article
Next Article

Similar Reads

Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Longest Common Subsequence with no repeating character
Given two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character. Examples: Input: s1= "aabbcc", s2= "aabc"Output: 3Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.So the required longest common subsequence with no repeating character is "abc". Input:
10 min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Longest Subsequence with absolute difference of pairs as at least Subsequence's maximum
Given an array arr[] of length N. The task is to find the length of the longest subsequence of the array such that the absolute difference between any pair of elements is greater than or equal to the maximum element in that subsequence. Examples: Input: N = 6, arr[] = {1, 1, 0, 0, 0, 0}Output: 4Explanation: Considering 0 as max element of subsequen
7 min read
Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
Given a sorted array of N integers. The task is to find the longest subsequence such that every element in the subsequence is reachable by multiplying any prime number to the previous element in the subsequence.Note: A[i] &lt;= 105 Examples: Input: a[] = {3, 5, 6, 12, 15, 36} Output 4 The longest subsequence is {3, 6, 12, 36} 6 = 3*2 12 = 6*2 36 =
15+ min read
Print Longest substring without repeating characters
Given a string, print the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. The desired time complexity is O(n) where n is the length of the string. Prerequisite: Length of
14 min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7 The desired time complexi
5 min read
Longest repeating and non-overlapping substring
Given a string str, find the longest repeating non-overlapping substring in it. In other words find 2 identical substrings of maximum length which do not overlap. If there exists more than one such substring return any of them. Examples: Input : str = "geeksforgeeks" Output : geeks Input : str = "aab" Output : a Input : str = "aabaabaaba" Output :
8 min read
Longest substring without repeating characters
Given a string s, find the length of the longest substring without repeating characters. Examples: Input: "ABCBC"Output: 3Explanation: The longest substring without repeating characters is "ABC"Input: "AAA"Output: 1Explanation: The longest substring without repeating characters is "A"Input: "GEEKSFORGEEKS"Output: 7 Explanation: The longest substrin
15+ min read
Maximum length subsequence such that adjacent elements in the subsequence have a common factor
Given an array arr[], the task is to find the maximum length of a subsequence such that the adjacent elements in the subsequence have a common factor. Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 } Output: 5Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 } Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 } Output: 6Max length subsequence
9 min read
Count maximum occurrence of subsequence in string such that indices in subsequence is in A.P.
Given a string S, the task is to count the maximum occurrence of subsequences in the given string such that the indices of the characters of the subsequence are Arithmetic Progression. Examples: Input: S = "xxxyy" Output: 6 Explanation: There is a subsequence "xy", where indices of each character of the subsequence are in A.P. The indices of the di
12 min read
Find the equal pairs of subsequence of S and subsequence of T
Given two arrays S[] and T[] of size N and M respectively. The task is to find the pairs of subsequences of S[] and subsequences of T[] which are the same in content. Answer could be very large. So, print the answer modulo 109 + 7.Examples: Input: S[] = {1, 1}, T[] = {1, 1} Output: 6 Subsequences of S[] are {}, {1}, {1} and {1, 1}. Subsequences of
13 min read
Construction of Longest Increasing Subsequence (N log N)
In my previous post, I have explained about longest increasing sub-sequence (LIS) problem in detail. However, the post only covered code related to querying size of LIS, but not the construction of LIS. I left it as an exercise. If you have solved, cheers. If not, you are not alone, here is code. If you have not read my previous post, read here. No
10 min read
Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation
Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it's explained very clearly here. In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN): Implementation: C/C++ Co
5 min read
Longest Bitonic Subsequence in O(n log n)
Given an array arr[0 … n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as an argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty
15+ min read
Longest subsequence having equal numbers of 0 and 1
Given a binary array, the task is to find the size of the largest sub_sequence which having equal number of zeros and one. Examples : Input : arr[] = { 1, 0, 0, 1, 0, 0, 0, 1 } Output: 6 Input : arr[] = { 0, 0, 1, 1, 1, 1, 1, 0, 0 }Output : 8 simple solution is that we generate all possible sub_sequence and find which sub_sequence have equal number
11 min read
Print Longest Palindromic Subsequence
Given a sequence, print a longest palindromic subsequence of it. Examples : Input : BBABCBCAB Output : BABCBAB The above output is the longest palindromic subsequence of given sequence. "BBBBB" and "BBCBB" are also palindromic subsequences of the given sequence, but not the longest ones. Input : GEEKSFORGEEKS Output : Output can be either EEKEE or
11 min read
Length of longest strict bitonic subsequence
Given an array arr[] containing n integers. The problem is to find the length of the longest strict bitonic subsequence. A subsequence is called strict bitonic if it is first increasing and then decreasing with the condition that in both the increasing and decreasing parts the absolute difference between adjacents is 1 only. A sequence, sorted in i
15+ min read
Longest Increasing Odd Even Subsequence
Given an array of size n. The problem is to find the length of the subsequence in the given array such that all the elements of the subsequence are sorted in increasing order and also they are alternately odd and even. Note that the subsequence could start either with the odd number or with the even number. Examples: Input : arr[] = {5, 6, 9, 4, 7,
8 min read
Longest Common Anagram Subsequence
Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to find the length of the longest subsequence which is present in both the strings in the form of anagrams. Note: The strings contain only lowercase letters. Examples: Input : str1 = "abdacp", str2 = "ckamb" Output : 3 Subsequence of str1 = abc Subsequence of str2 = ca
7 min read
Longest subsequence where each character occurs at least k times
Given a string 's' and an integer k, find other string 't' such that 't' is the largest subsequence of given string 's' and each character of 't' must occur at least k times in string s. Examples : Input : s = "geeksforgeeks" k = 2 Output : geeksgeeks Input : s = "baaabaacba" k = 3 Output : baaabaaba A simple solution is to generate all subsequence
5 min read
Range Queries for Longest Correct Bracket Subsequence
Given a bracket sequence or in other words a string S of length n, consisting of characters '(' and ')'. Find the length of the maximum correct bracket subsequence of sequence for a given query range Note: A correct bracket sequence is the one that has matched bracket pairs or which contains another nested correct bracket sequence. For e.g (), (())
15+ min read
Printing longest Increasing consecutive subsequence
Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} O
8 min read
Longest Decreasing Subsequence
Given an array of N integers, find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in strictly decreasing order. Examples: Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85] Output: 3 Explanation: The longest decreasing subsequence is {63, 55, 46} Input: arr[] = {50, 3, 10, 7, 40, 80}
14 min read
Length of longest subsequence having sum of digits of each element as a Composite Number
Given an array arr[] consisting of non-negative integers, the task is to print the length of the longest subsequence from the given array whose sum of digits of each element is a composite numbers. Examples: Input: arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 89}Output: 4Explanation: Following array elements have sum of digits equal to a composite numbe
9 min read
Longest Common Subsequence | DP using Memoization
Given two strings s1 and s2, the task is to find the length of the longest common subsequence present in both of them. Examples: Input: s1 = “ABCDGH”, s2 = “AEDFHR” Output: 3 LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4. Input: s1 = “striver”, s2 = “raj” Output: 1 The naive solution for this problem is to generate all subseq
13 min read
Longest subsequence whose average is less than K
Given an array of N positive integers and Q queries consisting of an integer K, the task is to print the length of the longest subsequence whose average is less than K. Examples: Input: a[] = {1, 3, 2, 5, 4} Query1: K = 3 Query2: K = 5 Output: 4 5 Query1: The subsequence is: {1, 3, 2, 4} or {1, 3, 2, 5} Query2: The subsequence is: {1, 3, 2, 5, 4} A
7 min read
Length of longest common subsequence containing vowels
Given two strings X and Y of length m and n respectively. The problem is to find the length of the longest common subsequence of strings X and Y which contains all vowel characters. Examples: Input : X = "aieef" Y = "klaief"Output : aieInput : X = "geeksforgeeks" Y = "feroeeks"Output : eoeeRecommended: Please try your approach on {IDE} first, befor
14 min read
Longest dividing subsequence
You are given an array A of size N. Your task is to find the length of largest dividing sub sequence.A dividing sequence is a sequence a1, a2, …, aN where ai divides aj whenever i &lt; j. For example, 3, 15, 60, 720 is a dividing sequence. input- The first line of each test case is N, where N is the size of array. The second line of each test case
5 min read
Longest Subsequence from a numeric String divisible by K
Given an integer K and a numeric string str, the task is to find the longest subsequence from the given string which is divisible by K. Examples: Input: str = "121400", K = 8Output: 121400Explanation:Since the whole string is divisible by 8, the entire string is the answer. Input: str: "7675437", K = 64Output: 64Explanation:The longest subsequence
8 min read