Longest Repeating Subsequence
Problem Statement
You are given a string s. Find the length of the longest subsequence that can be found twice in s. Two copies are picked from s by deleting letters. A letter from one place in s can be used by both copies, but only when it sits at different places inside the two copies. Return the length of the longest such subsequence.
A string s.
The length of the longest subsequence that can be picked twice from s under the rule above.
xx appears twice. One copy uses indexes 1 and 2. The other uses indexes 2 and 4. Index 2 is in both copies, but it is the second letter of one copy and the first letter of the other, so it is allowed.
Again xx. One copy uses indexes 1 and 2, and the other uses indexes 2 and 3. Index 2 is shared at different places.
- • 1 ≤ s.length ≤ 1000
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Two pointers walk through s: match when the letters agree at different indexes, else skip one
dp[i][j] for every pair of prefixes; a match needs i ≠ j
The same table in two rows; the diagonal (i = j) is never a match
Let f(i, j) be the answer when copy A may still use s[i..] and copy B may still use s[j..]. If i ≠ j and s[i] = s[j], the pair can be used as the next letter of both copies: 1 + f(i+1, j+1). Otherwise skip the next letter of one copy: max(f(i+1, j), f(i, j+1)).
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Strings translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.