What is LPS
A palindromic subsequence reads the same forwards and backwards; letters need not be contiguous. dp[i][j] is the LPS of the substring s[i..j]. Matching ends wrap a smaller palindrome; mismatch takes the better side.
Brute force approach
[i, j] match the ends and shrink, or drop one end. Same intervals repeat.If the ends match, both are kept and the inside is solved. Otherwise one end is dropped. The span (left, right) repeats. Memoization stores that span.
At most 5 letters. bbbab has length 4.
Memoized approach
2 + dp[i+1][j-1], else max of the two sides. Same as LCS(s, reverse(s)).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
bbbab. The interval table grows to 4 (bbbb). Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each interval | O(1) |
| All intervals | O(n²) |
| Space | O(n²) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations