Longest Repeating Subsequence

Given a string, find length of the longest repeating subseequence such that the two subsequence don’t have same string character at same position, i.e., any i’th 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 subssequence 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


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.

Below is the implementation of the idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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]*(n+1)]*(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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right



Output:

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

Another approach: (Using recursion)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
}

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

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

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.



My Personal Notes arrow_drop_up