Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 516 Longest Palindromic Subsequence - Walkthrough

Tracing the algorithm

Trace LPS on s="bbbab"s = \text{"bbbab"}. Build dp[i][j]dp[i][j] = LPS length for s[i..j]s[i..j]. Base cases: dp[i][i]=1dp[i][i] = 1 (single char).

Iterate by length. Length 22: dp[0][1]=2dp[0][1] = 2 ("bb"), dp[1][2]=2dp[1][2] = 2 ("bb"), dp[2][3]=1dp[2][3] = 1 ("ba"), dp[3][4]=1dp[3][4] = 1 ("ab"). Length 33, 44, 55: keep expanding. Final dp[0][4]=4dp[0][4] = 4. The LPS is "bbbb". The observation: when endpoints match, they contribute 22 to the palindrome length plus the inner solution.