Find Longest Recurring Subsequence in String

Pattern: Strings DP

medium

Find the longest subsequence that appears twice, using different positions for each copy. It is the LCS of the string with itself, except that a match must come from two different positions (i ≠ j).

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the length of the longest subsequence that occurs at least twice in s, where the two occurrences never use the same position for the same character.

Think first

  • Which two strings should be compared?
  • What stops a character matching itself?
  • What else stays the same?

Hints

    Brute force, and why it fails

    Try every subsequence and count its occurrences: exponential.

    The key insight

    Two copies at different positions are exactly an LCS of s with s where matches need i ≠ j.

    Dry run

    'axxzxy'. The two copies of 'xx' use positions (1, 2) and (2, 4).

    Step 1 of 2

    The plan

    dp[i][j] = dp[i-1][j-1] + 1 if s[i-1] == s[j-1] and i != j else max(dp[i-1][j], dp[i][j-1])
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    One LCS table.

    Edge cases

    • All different: 0.
    • All equal: n - 1.
    • One character: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int LongestRepeatingSubsequence(String s) {
            int n = s.length();
            int[][] dp = new int[n + 1][n + 1];     // LCS of s with itself, where a character may not pair with its own copy
            for (int i = 1; i <= n; i++)
                for (int j = 1; j <= n; j++)
                    dp[i][j] = s.charAt(i - 1) == s.charAt(j - 1) && i != j ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
            return dp[n][n];
        }
    }

    C++

    class Solution {
    public:
        int LongestRepeatingSubsequence(string s) {
            int n = static_cast<int>(s.size());
            vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));   // LCS of s with itself, never pairing a character with itself
            for (int i = 1; i <= n; i++)
                for (int j = 1; j <= n; j++)
                    dp[i][j] = s[i - 1] == s[j - 1] && i != j ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]);
            return dp[n][n];
        }
    };

    Python

    class Solution:
        def LongestRepeatingSubsequence(self, s: str) -> int:
            n = len(s)
            dp = [[0] * (n + 1) for _ in range(n + 1)]   # LCS of s with itself, never pairing a character with itself
            for i in range(1, n + 1):
                for j in range(1, n + 1):
                    dp[i][j] = dp[i - 1][j - 1] + 1 if s[i - 1] == s[j - 1] and i != j else max(dp[i - 1][j], dp[i][j - 1])
            return dp[n][n]

    Common mistakes

    • Allowing i = j, which gives n.
    • Confusing with repeated substrings.

    Similar problems