{"id":"longest-palindromic-subsequence","title":"Longest Palindromic Subsequence","difficulty":"medium","patterns":["dp-2d"],"primaryConcept":"dp-2d-strings","concepts":["dp-2d-strings"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string","primaryParam":"s","sizeMetric":"length","sizes":[8,16,32,64],"alphabet":"abcde"},"description":"Given a string `s`, return the length of the longest palindromic subsequence in `s`.\n\nA subsequence can delete characters without changing the order of the remaining characters.\n\nUse a 2D dynamic programming solution by comparing `s` with its reverse.","examples":[{"input":"s = \"bbbab\"","output":"4","explanation":"One longest palindromic subsequence is \"bbbb\"."},{"input":"s = \"cbbd\"","output":"2","explanation":"The longest palindromic subsequence is \"bb\"."}],"constraints":[{"id":"1-len-s-1000","text":"1 <= len(s) <= 1000","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":1000}},{"id":"s-consists-only-of-lowercase-english-letters","text":"s consists only of lowercase English letters","check":{"kind":"domain","target":"s","selector":"stringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]}}],"starterCode":"class Solution:\n    def longestPalindromeSubseq(self, s: str) -> int:\n        # Your code here\n        pass","functionName":"longestPalindromeSubseq","testCases":[{"id":"1","input":{"s":"bbbab"},"expected":4,"description":"Classic sample with a repeated-character palindrome."},{"id":"2","input":{"s":"cbbd"},"expected":2,"description":"The best subsequence is the middle pair."},{"id":"3","input":{"s":"a"},"expected":1,"description":"A single character is already a palindrome."},{"id":"4","input":{"s":"agbdba"},"expected":5,"description":"The subsequence abdba has length five."},{"id":"5","input":{"s":"abcde"},"expected":1,"description":"No two matching letters can form a longer palindrome."},{"id":"6","input":{"s":"aaaa"},"expected":4,"description":"The whole string is palindromic."},{"id":"hidden-1","input":{"s":"euazbipzncptlduekgxy"},"expected":7,"description":"Longer mixed string."},{"id":"hidden-2","input":{"s":"abcba"},"expected":5,"description":"The whole hidden string is already palindromic."},{"id":"hidden-3","input":{"s":"banana"},"expected":5,"description":"The best subsequence skips the first character."},{"id":"hidden-4","input":{"s":"racecarx"},"expected":7,"description":"A full palindrome can be preserved while ignoring a trailing character."},{"id":"non-adjacent-classic","input":{"s":"character"},"expected":5,"description":"The best palindrome uses non-adjacent matches inside the string."},{"id":"dense-overlapping-palindromes","input":{"s":"bbabcbcab"},"expected":7,"description":"Dense repeated letters create several overlapping optimal choices."}],"hints":[{"level":1,"content":"A palindrome reads the same forward and backward."},{"level":2,"content":"Compare the string against its reverse, then find the longest common subsequence."},{"level":3,"content":"When the characters match, extend the diagonal predecessor; otherwise keep the best adjacent predecessor."}],"guidedFlow":{"version":2,"progressRevision":"longest-palindromic-subsequence-2026-07-19-state-definition","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Pick the approach whose work matches the n up to 1000 the constraints allow.","approaches":[{"id":"lcs-reduction","name":"Overlap the string with its reverse","summary":"Reverse the string and fill a table whose cell holds the best overlap between a prefix of the string and a prefix of the reverse.","decisionReason":"A palindromic subsequence is exactly a sequence shared, in order, between the string and its reverse, so the longest one is the overlap in the bottom-right cell. Each cell extends a smaller one, so the table fills in a single sweep.","complexity":{"time":"O(n^2)","space":"O(n^2)"},"tradeoffs":["Fills one cell per prefix pair, so O(n^2) time and O(n^2) space, well within n up to 1000."],"isOptimal":true},{"id":"try-all-subsequences","name":"Try every subsequence","summary":"Generate every subsequence of the string and keep the longest one that reads the same backward.","decisionReason":"Every character is kept or dropped independently, so this enumerates about 2^n subsequences and checks each for being a palindrome, which blows past n = 1000.","complexity":{"time":"O(2^n)","space":"O(n)"},"tradeoffs":["Enumerates roughly 2^n subsequences, far too many once n grows past about 20."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-dp-table","title":"Reverse the string and build the table","description":"Store reverse(s), read n, then create an (n+1) by (n+1) grid of zeros.","commonMistakes":["Allocating only one dimension instead of a grid","Forgetting the extra zero row and column for empty prefixes"],"hint":"The overlap of two empty prefixes is zero, so the extra border row and column start at zero.","semanticSpec":{"intent":"Initialize a 2D DP table.","doneWhen":"A grid-shaped DP table is initialized before recurrence loops.","shouldFailWhen":"No indexed DP table is created.","roles":["dp table","prefix lengths"],"mustProve":["Grid DP table initialization exists."],"mustNotAccept":["Only a scalar answer variable."],"equivalentVariants":["Use a list of lists, array of arrays, or equivalent 2D matrix."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"s","secondAxisInputState":"s","firstAxisOffset":1,"secondAxisOffset":1}}]}},{"id":"nested-loops","title":"Sweep every prefix pair","description":"Loop the row index and the column index from 1, visiting each interior cell once.","commonMistakes":["Starting a loop at zero and then reading one position back out of range","Sweeping only one of the two dimensions"],"hint":"Each cell depends only on smaller prefix pairs, so fill them in increasing order.","semanticSpec":{"intent":"Fill the interior of the DP grid.","doneWhen":"Nested loops visit interior DP cells.","shouldFailWhen":"Only one dimension is scanned.","roles":["row index","column index"],"mustProve":["The recurrence loops over interior grid cells."],"mustNotAccept":["A single flat scan."],"equivalentVariants":["Use one-based DP indices over zero-based string characters."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]}},{"id":"extend-match","title":"Extend the diagonal on a match","description":"When the current characters of s and its reverse are equal, set the cell to the diagonal predecessor plus one.","commonMistakes":["Reading a side neighbor instead of the diagonal on a match","Forgetting to add one for the newly matched character"],"hint":"A matched character is one more shared character on top of the best for both prefixes without it.","semanticSpec":{"intent":"Apply the match transition.","doneWhen":"A match writes diagonal predecessor plus one.","shouldFailWhen":"Matches do not extend the subsequence length.","roles":["diagonal predecessor","current DP cell"],"mustProve":["The diagonal predecessor is extended for matching characters."],"mustNotAccept":["Always taking a max of side predecessors."],"equivalentVariants":["Use any equivalent diagonal DP transition."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"extends_diagonal_predecessor","scope":"dp-update-match","readMode":"dp-value-query-v1"}]}},{"id":"keep-best-mismatch","title":"Keep the larger neighbor on a mismatch","description":"When the characters differ, set the cell to the larger of the neighbor above and the neighbor to the left.","commonMistakes":["Taking the smaller neighbor instead of the larger","Resetting the cell to zero, which solves substrings rather than subsequences"],"hint":"A mismatch means one side skips its current character, so inherit the better of the two skips.","semanticSpec":{"intent":"Apply the mismatch transition.","doneWhen":"A mismatch writes the extremum of adjacent predecessor cells.","shouldFailWhen":"Mismatches reset the cell or use the wrong predecessor.","roles":["top predecessor","left predecessor","current DP cell"],"mustProve":["Adjacent predecessor maximum is used on mismatch."],"mustNotAccept":["Ignoring one adjacent predecessor."],"equivalentVariants":["Use `max(top, left)` or equivalent comparison logic."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"takes_adjacent_predecessor_extremum","scope":"dp-update-no-match","readMode":"dp-value-query-v1"}]}},{"id":"return-result","title":"Return the bottom-right cell","description":"After the sweep, return the cell for the whole string against its whole reverse.","commonMistakes":["Returning the whole table instead of one cell","Returning the string length instead of the computed overlap"],"hint":"The last cell holds the overlap of all of s with all of reverse(s).","semanticSpec":{"intent":"Return the completed DP answer.","doneWhen":"The function returns the bottom-right DP cell.","shouldFailWhen":"The return value is not the full-prefix DP result.","roles":["bottom-right cell"],"mustProve":["The final DP cell is returned."],"mustNotAccept":["Returning a partially filled row or column."],"equivalentVariants":["Return `dp[n][n]` or an equivalent full-prefix terminal cell."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_bottom_right_cell","scope":"return-answer","readMode":"dp-value-query-v1"}]}}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The string","eyebrow":"Read the problem","title":"The longest palindrome you can keep","workspacePanel":"problem","body":["Given a string, find the length of the longest subsequence that reads the same forward and backward. A subsequence deletes any characters it likes but keeps the rest in order.","Matching end characters can surround a smaller palindrome. When the ends differ, one of them must be dropped, and those choices repeatedly ask about the same inner ranges."]},{"id":"brute","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Match the ends, or drop one","workspacePanel":"trace","summary":"Look at the two ends of a range and decide what the best palindrome inside it can be.","body":["The direct approach looks at the outer characters of a range. When they are equal, both can wrap a palindrome, so it keeps them and shrinks inward. When they differ, at least one end is wasted, so it tries dropping each end and keeps the longer result."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def longestPalindromeSubseq(s: str) -> int:\n    def best(i: int, j: int) -> int:\n        if i > j:\n            return 0\n        if i == j:\n            return 1\n        if s[i] == s[j]:\n            return 2 + best(i + 1, j - 1)\n        return max(best(i + 1, j), best(i, j - 1))\n    return best(0, len(s) - 1)","steps":[{"id":"brute-match","title":"\"b\" equals \"b\" at the ends: keep both, move inward","codeLine":8,"summary":"On s = \"bba\" the range from i = 0 to j = 2 has ends \"b\" and \"a\", which differ, so look one step in: the range \"bb\" has equal ends, worth 2 plus the inside.","state":{"arrays":[{"name":"s","values":["b","b","a"],"left":0,"right":1}],"labels":{"left":"i","right":"j"}}},{"id":"brute-branch","title":"\"b\" vs \"a\" differ: try dropping each end","codeLine":9,"summary":"Back on the full range, the ends \"b\" and \"a\" differ, so the call splits into dropping the right end and dropping the left end, keeping the larger.","state":{"arrays":[{"name":"s","values":["b","b","a"],"left":0,"right":2}],"labels":{"left":"i","right":"j"}}},{"id":"brute-again","title":"The same inner range gets solved again","codeLine":9,"summary":"Both of those branches eventually ask for the best palindrome in the middle range \"b\", recomputing the same subproblem from scratch.","state":{"arrays":[{"name":"s","values":["b","b","a"],"left":1,"right":1}],"labels":{"left":"i","right":"j"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function best(i, j) {\n    if (i > j) {\n        return 0;\n    }\n    if (i === j) {\n        return 1;\n    }\n    if (s[i] === s[j]) {\n        return (2 + best((i + 1), (j - 1)));\n    }\n    return Math.max(best((i + 1), j), best(i, (j - 1)));\n}\nreturn best(0, (s.length - 1));","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":11,"10":13},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"9":{"startLine":11,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function best(i: number, j: number): number {\n    if (i > j) {\n        return 0;\n    }\n    if (i === j) {\n        return 1;\n    }\n    if (s[i] === s[j]) {\n        return (2 + best((i + 1), (j - 1)));\n    }\n    return Math.max(best((i + 1), j), best(i, (j - 1)));\n}\nreturn best(0, (s.length - 1));","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":11,"10":13},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"9":{"startLine":11,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int Best(int i, int j) {\n    if (i > j) {\n        return 0;\n    }\n    if (i == j) {\n        return 1;\n    }\n    if (s[i] == s[j]) {\n        return 2 + Best(i + 1, j - 1);\n    }\n    return Math.Max(Best(i + 1, j), Best(i, j - 1));\n    return 0;\n}\nreturn Best(0, s.Length - 1);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":11,"10":14},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"9":{"startLine":11,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int)> best;\n\nbest = [&]( int i, int j ) -> int {\n    if (i > j) {\n        return 0;\n    }\n    if (i == j) {\n        return 1;\n    }\n    if (s[i] == s[j]) {\n        return (2 + best((i + 1), (j - 1)));\n    }\n    return max(best((i + 1), j), best(i, (j - 1)));\n};\nreturn best(0, (s.size() - 1));","lineMap":{"3":4,"4":5,"5":7,"6":8,"7":10,"8":11,"9":13,"10":15},"statementBundles":{"4":{"startLine":5,"endLine":6},"6":{"startLine":8,"endLine":9},"8":{"startLine":11,"endLine":12},"9":{"startLine":13,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int best(int i, int j, String s) {\n    if (i > j) {\n        return 0;\n    }\n    if (i == j) {\n        return 1;\n    }\n    if (s.charAt(i) == s.charAt(j)) {\n        return (2 + best((i + 1), (j - 1), s));\n    }\n    return Math.max(best((i + 1), j, s), best(i, (j - 1), s));\n}\n\nreturn best(0, (s.length() - 1), s);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":11,"10":14},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"9":{"startLine":11,"endLine":12}}}}}},{"id":"brute-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the work","title":"Every differing pair of ends forks into two calls. How does the work grow with n?","workspacePanel":"visualizer","summary":"We just watched the same inner range get re-solved from scratch.","options":[{"id":"exponential","label":"Exponentially: each differing pair of ends doubles the branches","rationale":"On a mismatch the call splits into dropping the left end and dropping the right end, and those branches re-solve overlapping inner ranges from scratch, so the calls compound to roughly 2^n.","isCorrect":true},{"id":"quadratic","label":"About n squared, one call per range","rationale":"There are only about n^2 distinct ranges, but nothing remembers them yet, so each differing pair forks and re-solves the same range many times, which compounds far past n^2."},{"id":"linear","label":"About n, one per character","rationale":"A single pass would suffice only without branching; every differing pair of ends forks into two calls, so the work compounds far past n."}],"answer":"Exponentially. Each differing pair of ends forks into two calls that re-solve overlapping inner ranges, so the recursion repeats the same subproblems and the work compounds to roughly 2^n. Yet there are only about n^2 distinct ranges, which is the opening to remember each one once.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fork-state","state":{"arrays":[{"name":"s","values":["b","b","a"],"left":0,"right":2,"labels":{"left":"i","right":"j"}}]}}]}},{"id":"palindrome-is-overlap","kind":"case-probe","chapter":"The trick","eyebrow":"Find the angle","title":"A palindrome reads the same backward. What does that make it, against reverse(s)?","workspacePanel":"visualizer","summary":"Use s = \"bbbab\" and the mirrored copy below it.","options":[{"id":"shared","label":"A sequence shared, in order, by s and reverse(s)","rationale":"Reading a palindrome backward gives the same string, so it appears in s and just as well in reverse(s); the longest such shared sequence is the longest palindromic subsequence.","isCorrect":true},{"id":"prefix","label":"A prefix of reverse(s)","rationale":"A palindrome need not sit at the front; it can use characters scattered through the string, so it is not a prefix of the reverse."},{"id":"contiguous","label":"A contiguous block that equals its mirror block","rationale":"That describes a palindromic substring; a subsequence may skip characters, so it is not a contiguous block."}],"answer":"A sequence shared by both, in order. A palindrome is unchanged when reversed, so it lives in s and in reverse(s) alike, and the longest one shared by the two is the answer.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"overlap-state","state":{"arrays":[{"name":"s","values":["b","b","a"]},{"name":"reverse(s)","values":["a","b","b"]}]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which approach should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"table-bridge","kind":"info","chapter":"The idea","eyebrow":"Set up the table","title":"One cell per pair of prefixes","workspacePanel":"visualizer","body":["So the job becomes finding the longest sequence shared, in order, by s and reverse(s). The repeated subproblems are pairs of prefixes, so give each prefix pair one table cell.","Before filling the table, settle exactly which question one cell answers."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"table-bridge-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"state-definition","chapter":"The idea","kind":"case-probe","eyebrow":"Define the table","title":"What should dp[i][j] mean?","summary":"The row chooses the first i characters of s, and the column chooses the first j characters of reverse(s).","workspacePanel":"visualizer","options":[{"id":"best-prefix-overlap","label":"The longest subsequence shared by those two prefixes","rationale":"Each cell records the complete answer for one prefix pair. That lets later cells reuse it whether their current characters match or differ.","isCorrect":true},{"id":"path-so-far","label":"The number of matches collected along the current recursive path","rationale":"Different paths can reach the same prefix pair with different histories. The cell must hold the best answer for the pair itself, independent of how it was reached."},{"id":"characters-equal","label":"Whether the two current characters are equal","rationale":"Character equality chooses the recurrence case, but the problem asks for a length. The cell must store the best shared-subsequence length for the whole prefix pair."}],"answer":"dp[i][j] is the longest subsequence shared by s's first i characters and reverse(s)'s first j characters. The bottom-right cell therefore answers the original problem.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-definition-grid","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":2,"c":2,"labels":{"grid":"dp"}}}]}},{"id":"match-or-not","kind":"case-probe","chapter":"The idea","eyebrow":"Find the cases","title":"Comparing the last character of each prefix, what are the only two cases?","workspacePanel":"visualizer","summary":"dp[i][j] is filled from the last character of s's prefix and the last of the reverse's prefix.","options":[{"id":"two","label":"The two characters are equal, or they are not","rationale":"Equality is the single fork: matching characters can both join the shared sequence, unequal ones cannot both end it.","isCorrect":true},{"id":"three","label":"Equal, earlier in the alphabet, or later","rationale":"The characters are tested only for equality here; their alphabetical order plays no part in the recurrence."},{"id":"len","label":"The two prefixes are the same length, or not","rationale":"Prefix length does not drive the rule; whether the two current characters match does."}],"answer":"They match or they do not. That single test decides whether both characters can extend the shared sequence.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cases-state","state":{"arrays":[{"name":"s","values":["b","b","a"],"i":0,"labels":{"i":"s[i-1]"}},{"name":"reverse(s)","values":["a","b","b"],"i":0,"labels":{"i":"rev[j-1]"}}],"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"match-diagonal","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"When the two characters match, which earlier answer does the cell extend?","workspacePanel":"visualizer","summary":"The current characters are equal, so both can join the shared sequence.","options":[{"id":"diagonal","label":"The diagonal: both prefixes without these two characters, plus 1","rationale":"Dropping the matched character from each side leaves the smaller prefix pair, the diagonal cell, and the match adds one to it.","isCorrect":true},{"id":"up","label":"The cell above, plus 1","rationale":"The cell above drops a character from only one side; a match consumes a character from both, which is the diagonal."},{"id":"same","label":"The same cell, plus 1","rationale":"A cell cannot build on itself; the match builds on the strictly smaller diagonal prefix pair."}],"answer":"The diagonal plus 1. Equal characters extend the best shared sequence of both prefixes without them, dp[i-1][j-1] + 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"match-state","state":{"grid":[[0,0,0,0],[0,0,1,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,2]],"frontier":[[0,1]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"no-match-max","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"When the characters differ, the cell is the better of which two?","workspacePanel":"visualizer","summary":"A mismatch leaves at least one of the two current characters unused.","options":[{"id":"up-left","label":"The cell above and the cell to the left","rationale":"Dropping the last character of one prefix or the other gives the two candidates, and the larger of them wins.","isCorrect":true},{"id":"diagonal","label":"The diagonal cell","rationale":"The diagonal drops a character from both prefixes at once, throwing away one that might still be usable on a side."},{"id":"sum","label":"The cell above plus the cell to the left","rationale":"Adding the two double-counts what they share; only one dropped-character choice is taken, so the cell keeps the larger value."}],"answer":"The larger of above and left. A mismatch drops the last character of one prefix or the other, so dp takes max(dp[i-1][j], dp[i][j-1]).","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"nomatch-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1]],"frontier":[[0,1],[1,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"An empty prefix shares nothing","workspacePanel":"visualizer","body":["The table has a row and a column for the empty prefix, all zeros: anything against nothing shares no characters.","Tracing s = \"bba\" against reverse(s) = \"abb\", each interior cell either extends the diagonal on a match or keeps the larger of its top and left neighbors."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Fill the table","title":"Fill the overlap table","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cell-11","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"frontier":[[0,1],[1,0]],"labels":{"grid":"dp"},"changed":[]}},{"id":"cell-12","state":{"grid":[[0,0,0,0],[0,0,1,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2]],"labels":{"grid":"dp"},"changed":[]}},{"id":"cell-23","state":{"grid":[[0,0,0,0],[0,0,1,1],[0,0,1,2],[0,0,0,0]],"r":2,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3]],"labels":{"grid":"dp"},"changed":[]}},{"id":"cell-33","state":{"grid":[[0,0,0,0],[0,0,1,1],[0,0,1,2],[0,1,1,2]],"r":3,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]],"labels":{"grid":"dp"},"changed":[]}}]},"beats":[{"id":"cell-11","title":"Cell (1,1): \"b\" vs \"a\". Match or mismatch, and what fills it?","summary":"The first interior cell.","prompt":"s's first character \"b\" meets reverse(s)'s first character \"a\".","options":[{"id":"zero","label":"Mismatch, so max(above 0, left 0) = 0","rationale":"\"b\" and \"a\" differ, so the cell keeps the larger neighbor, and both are 0.","isCorrect":true},{"id":"one","label":"Match, so diagonal + 1 = 1","rationale":"\"b\" and \"a\" are not equal, so there is no match to extend the diagonal."},{"id":"edge","label":"It stays empty, off the table","rationale":"It is a real interior cell; it computes to 0 by the mismatch rule."}],"answer":"Mismatch. \"b\" and \"a\" differ, so the cell is max(0, 0) = 0."},{"id":"cell-12","title":"Cell (1,2): \"b\" vs \"b\". What now?","summary":"The characters line up.","prompt":"s's \"b\" meets reverse(s)'s second character \"b\".","options":[{"id":"diag","label":"Match, so diagonal (0) + 1 = 1","rationale":"Equal characters extend the diagonal prefix pair, which holds 0, giving 1.","isCorrect":true},{"id":"max","label":"Take max(above 0, left 0) = 0","rationale":"That is the mismatch rule; on a match the cell extends the diagonal instead."},{"id":"two","label":"Diagonal + 2","rationale":"A single matched character adds exactly 1 to the diagonal, not 2."}],"answer":"Match. \"b\" equals \"b\", so diagonal 0 + 1 = 1."},{"id":"cell-23","title":"Cell (2,3): \"b\" vs \"b\" again. Which rule runs, and what does it read?","summary":"This cell has a nonzero predecessor near it.","prompt":"s's second \"b\" meets reverse(s)'s third \"b\"; read the needed predecessor off the table.","options":[{"id":"two","label":"Match, so diagonal (1) + 1 = 2","rationale":"Equal characters add one to the diagonal, which already holds 1, so the cell becomes 2, the two b's kept so far.","isCorrect":true},{"id":"one","label":"Match, but it stays 1","rationale":"A match always adds one to the diagonal; since the diagonal is 1 here, the cell rises to 2."},{"id":"max","label":"Mismatch, so max of the neighbors","rationale":"The characters are equal, so the match branch runs and extends the diagonal predecessor."}],"answer":"2. The characters match and the diagonal already holds 1, so 1 + 1 = 2."},{"id":"cell-33","title":"The corner: \"a\" vs \"b\". Which rule runs, and which neighbors does it weigh?","summary":"The bottom-right cell holds the final length.","prompt":"s's last character \"a\" meets reverse(s)'s last character \"b\"; read the neighbors this branch needs off the table.","options":[{"id":"two","label":"Mismatch, so max(2, 1) = 2","rationale":"The characters differ, so the cell keeps the larger neighbor, 2, the length of the palindrome \"bb\".","isCorrect":true},{"id":"one","label":"Mismatch, so the left neighbor 1","rationale":"The mismatch rule keeps the larger of the two neighbors, and 2 above beats 1 to the left."},{"id":"three","label":"Match, so diagonal + 1","rationale":"\"a\" and \"b\" are not equal, so there is no diagonal extension here."}],"answer":"2. The corner is a mismatch, so max(2, 1) = 2, the longest palindromic subsequence of \"bba\", which is \"bb\"."}]},{"id":"substring-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Why not reset the cell to 0 on a mismatch?","summary":"Resetting to 0 whenever the characters differ feels natural, and it is exactly right for a neighboring problem, the longest palindromic substring, where the kept characters must be contiguous. Borrow that rule here and watch it on \"bxab\", whose best palindrome \"bab\" has a gap in the middle.","pitfall":"The code below sets the cell to 0 on a mismatch instead of carrying the larger neighbor.","whyItMatters":"The palindrome \"bab\" skips the x in \"bxab\", so its answer is 3. The reset rule wipes the diagonal at every gap and reports 1, the longest run with no skip. Carrying max(above, left) across a mismatch is exactly what lets the subsequence jump the gap and keep its earlier progress.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def longestPalindromeSubseq(s: str) -> int:\n    reverse_s = s[::-1]\n    n = len(s)\n    dp = [[0] * (n + 1) for _ in range(n + 1)]\n    for i in range(1, n + 1):\n        for j in range(1, n + 1):\n            if s[i - 1] == reverse_s[j - 1]:\n                dp[i][j] = dp[i - 1][j - 1] + 1\n            else:\n                dp[i][j] = 0\n    return dp[n][n]","steps":[{"id":"match-b","title":"\"b\" matches \"b\": the cell becomes 1","codeLine":8,"summary":"The diagonal extension works on a match, starting the count at 1.","state":{"grid":[[0,0,0,0,0],[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[2,0],[3,0],[4,0],[1,1]],"labels":{"grid":"dp"},"changed":[]}},{"id":"reset","title":"\"x\" vs \"a\" mismatches: the cell is forced to 0","codeLine":10,"summary":"The progress built up to the left is thrown away instead of carried forward.","state":{"grid":[[0,0,0,0,0],[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]],"r":2,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[2,0],[3,0],[4,0],[1,1],[1,2],[1,3],[1,4],[2,1],[2,2]],"labels":{"grid":"dp"},"changed":[]}},{"id":"wrong","title":"The corner reports 1, not 3","codeLine":8,"summary":"Every gap reset the count, so the table never carries \"bab\" across the x, and the answer collapses to 1.","state":{"grid":[[0,0,0,0,0],[0,1,0,0,1],[0,0,0,1,0],[0,0,1,0,0],[0,1,0,0,1]],"r":4,"c":4,"filled":[[0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[2,0],[3,0],[4,0],[1,1],[1,2],[1,3],[1,4],[2,1],[2,2],[2,3],[2,4],[3,1],[3,2],[3,3],[3,4],[4,1],[4,2],[4,3],[4,4]],"labels":{"grid":"dp"},"changed":[]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const reverseS = [...s].reverse().join(\"\");\nconst n = s.length;\nconst dp = Array.from({ length: (n + 1) }, () => Array((n + 1)).fill(0));\nfor (let i = 1; i < (n + 1); i++) {\n    for (let j = 1; j < (n + 1); j++) {\n        if (s[(i - 1)] === reverseS[(j - 1)]) {\n            dp[i][j] = (dp[(i - 1)][(j - 1)] + 1);\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[n][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const reverseS = [...s].reverse().join(\"\");\nconst n = s.length;\nconst dp = Array.from({ length: (n + 1) }, () => Array((n + 1)).fill(0));\nfor (let i = 1; i < (n + 1); i++) {\n    for (let j = 1; j < (n + 1); j++) {\n        if (s[(i - 1)] === reverseS[(j - 1)]) {\n            dp[i][j] = (dp[(i - 1)][(j - 1)] + 1);\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[n][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"String reverseS = new StringBuilder(String.valueOf(s)).reverse().toString();\nint n = s.length();\nList<List<Integer>> dp = new ArrayList<>();\nfor (int i = 0; i < (n + 1); i++) {\n    List<Integer> items0 = new ArrayList<>();\n    for (int index = 0; index < (n + 1); index++) {\n        items0.add(0);\n    }\n    dp.add(items0);\n}\nfor (int i = 1; i < (n + 1); i++) {\n    for (int j = 1; j < (n + 1); j++) {\n        if (s.charAt(i - 1) == reverseS.charAt(j - 1)) {\n            dp.get(i).set(j, (dp.get(i - 1).get(j - 1) + 1));\n        } else {\n            dp.get(i).set(j, 0);\n        }\n    }\n}\nreturn dp.get(n).get(n);","lineMap":{"2":1,"3":2,"4":3,"5":11,"6":12,"7":13,"8":14,"9":15,"10":16,"11":20},"statementBundles":{"4":{"startLine":3,"endLine":10},"10":{"startLine":16,"endLine":19}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"string reverseS = new(s.Reverse().ToArray());\nint n = s.Length;\nList<List<int>> dp = Enumerable.Range(0, n + 1).Select(_ => Enumerable.Repeat<int>(0, n + 1).ToList()).ToList();\nfor (int i = 1; i < n + 1; i++) {\n    for (int j = 1; j < n + 1; j++) {\n        if (s[i - 1] == reverseS[j - 1]) {\n            dp[i][j] = dp[i - 1][j - 1] + 1;\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[n][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"string reverse_s = s;\nreverse(reverse_s.begin(), reverse_s.end());\nint n = s.size();\nvector<vector<int>> dp = vector<vector<int>>((n + 1), vector<int>((n + 1), 0));\nfor (int i = 1; i < (n + 1); i++) {\n    for (int j = 1; j < (n + 1); j++) {\n        if (s[(i - 1)] == reverse_s[(j - 1)]) {\n            dp[i][j] = (dp[(i - 1)][(j - 1)] + 1);\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[n][n];","lineMap":{"2":1,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":14},"statementBundles":{"2":{"startLine":1,"endLine":2},"10":{"startLine":10,"endLine":13}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["A match extending the diagonal and a mismatch keeping the larger neighbor filled the whole table from the zero border.","The extreme strings are the ones to stress, so try a string where every character is the same, and a string where no character repeats at all."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"all-same-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"When every character is the same, what answer comes back?","workspacePanel":"visualizer","summary":"s = \"aaaa\", and its reverse is identical.","options":[{"id":"len","label":"4, the whole string","rationale":"Each character matches on the diagonal against the identical reverse, so the diagonal climbs 1, 2, 3, 4 and the whole string is already a palindrome.","isCorrect":true},{"id":"one","label":"1, a single character","rationale":"Matches accumulate along the diagonal, each adding 1, so the answer is the full length rather than 1."},{"id":"two","label":"2, one matched pair","rationale":"Every character can be kept, so the palindrome is the entire string. A pair would leave one matching character unused."}],"answer":"4. All characters equal means s equals its reverse, so the diagonal climbs to the full length.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"allsame-state","state":{"arrays":[{"name":"s","values":["a","a","a","a"]},{"name":"reverse(s)","values":["a","a","a","a"]}],"grid":[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[2,0],[3,0],[4,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"no-repeats-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"When no character repeats, what answer comes back?","workspacePanel":"visualizer","summary":"s = \"abcd\", whose reverse is \"dcba\".","options":[{"id":"one","label":"1, any single character","rationale":"Each character of s appears once in the reverse, so exactly one match lands per character and the table never rises above 1.","isCorrect":true},{"id":"zero","label":"0, nothing is a palindrome","rationale":"A single character is itself a palindrome of length 1, so the answer is at least 1."},{"id":"four","label":"4, the whole string","rationale":"With no repeats, no two positions can mirror each other, so only a length-1 palindrome survives."}],"answer":"1. With no repeats, each character matches the reverse exactly once, so the best palindrome is a single character.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"norep-state","state":{"arrays":[{"name":"s","values":["a","b","c","d"]},{"name":"reverse(s)","values":["d","c","b","a"]}],"grid":[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[2,0],[3,0],[4,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Reverse once, then one comparison per cell decides match or mismatch.","body":["Reverse the string, then build a table with an extra zero row and column for the empty prefixes. Sweep the interior in order.","If the current characters of s and its reverse match, the cell is the diagonal plus 1; otherwise it is the larger of the cell above and the cell to its left. Return the bottom-right cell."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]},"ctaLabel":"Start coding"},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the overlap table","eyebrow":"Code the rule","summary":"Now write it: reverse the string and lay out the zero-bordered table, sweep every prefix pair, and at each cell extend the diagonal on a match or keep the larger neighbor on a mismatch, then return the bottom-right cell.","workspacePanel":"code","checkpoints":[{"id":"init-dp-table","title":"Reverse the string and build the table","description":"Store reverse(s), read n, then create an (n+1) by (n+1) grid of zeros.","commonMistakes":["Allocating only one dimension instead of a grid","Forgetting the extra zero row and column for empty prefixes"],"hint":"The overlap of two empty prefixes is zero, so the extra border row and column start at zero.","semanticSpec":{"intent":"Initialize a 2D DP table.","doneWhen":"A grid-shaped DP table is initialized before recurrence loops.","shouldFailWhen":"No indexed DP table is created.","roles":["dp table","prefix lengths"],"mustProve":["Grid DP table initialization exists."],"mustNotAccept":["Only a scalar answer variable."],"equivalentVariants":["Use a list of lists, array of arrays, or equivalent 2D matrix."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"s","secondAxisInputState":"s","firstAxisOffset":1,"secondAxisOffset":1}}]}},{"id":"nested-loops","title":"Sweep every prefix pair","description":"Loop the row index and the column index from 1, visiting each interior cell once.","commonMistakes":["Starting a loop at zero and then reading one position back out of range","Sweeping only one of the two dimensions"],"hint":"Each cell depends only on smaller prefix pairs, so fill them in increasing order.","semanticSpec":{"intent":"Fill the interior of the DP grid.","doneWhen":"Nested loops visit interior DP cells.","shouldFailWhen":"Only one dimension is scanned.","roles":["row index","column index"],"mustProve":["The recurrence loops over interior grid cells."],"mustNotAccept":["A single flat scan."],"equivalentVariants":["Use one-based DP indices over zero-based string characters."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]}},{"id":"extend-match","title":"Extend the diagonal on a match","description":"When the current characters of s and its reverse are equal, set the cell to the diagonal predecessor plus one.","commonMistakes":["Reading a side neighbor instead of the diagonal on a match","Forgetting to add one for the newly matched character"],"hint":"A matched character is one more shared character on top of the best for both prefixes without it.","semanticSpec":{"intent":"Apply the match transition.","doneWhen":"A match writes diagonal predecessor plus one.","shouldFailWhen":"Matches do not extend the subsequence length.","roles":["diagonal predecessor","current DP cell"],"mustProve":["The diagonal predecessor is extended for matching characters."],"mustNotAccept":["Always taking a max of side predecessors."],"equivalentVariants":["Use any equivalent diagonal DP transition."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"extends_diagonal_predecessor","scope":"dp-update-match","readMode":"dp-value-query-v1"}]}},{"id":"keep-best-mismatch","title":"Keep the larger neighbor on a mismatch","description":"When the characters differ, set the cell to the larger of the neighbor above and the neighbor to the left.","commonMistakes":["Taking the smaller neighbor instead of the larger","Resetting the cell to zero, which solves substrings rather than subsequences"],"hint":"A mismatch means one side skips its current character, so inherit the better of the two skips.","semanticSpec":{"intent":"Apply the mismatch transition.","doneWhen":"A mismatch writes the extremum of adjacent predecessor cells.","shouldFailWhen":"Mismatches reset the cell or use the wrong predecessor.","roles":["top predecessor","left predecessor","current DP cell"],"mustProve":["Adjacent predecessor maximum is used on mismatch."],"mustNotAccept":["Ignoring one adjacent predecessor."],"equivalentVariants":["Use `max(top, left)` or equivalent comparison logic."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"takes_adjacent_predecessor_extremum","scope":"dp-update-no-match","readMode":"dp-value-query-v1"}]}},{"id":"return-result","title":"Return the bottom-right cell","description":"After the sweep, return the cell for the whole string against its whole reverse.","commonMistakes":["Returning the whole table instead of one cell","Returning the string length instead of the computed overlap"],"hint":"The last cell holds the overlap of all of s with all of reverse(s).","semanticSpec":{"intent":"Return the completed DP answer.","doneWhen":"The function returns the bottom-right DP cell.","shouldFailWhen":"The return value is not the full-prefix DP result.","roles":["bottom-right cell"],"mustProve":["The final DP cell is returned."],"mustNotAccept":["Returning a partially filled row or column."],"equivalentVariants":["Return `dp[n][n]` or an equivalent full-prefix terminal cell."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_bottom_right_cell","scope":"return-answer","readMode":"dp-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"A palindromic subsequence is a sequence shared with the reverse, so each cell extends the diagonal on a match and keeps the larger neighbor on a mismatch.","workspacePanel":"code","body":["Reversing the string turns \"longest palindrome\" into \"longest sequence shared with the reverse\", a 2D table indexed by the two prefix lengths.","The match-versus-mismatch fork is the whole algorithm: a match consumes one character from each side and extends the diagonal, a mismatch drops one and keeps the better neighbor."],"takeaways":[{"title":"A palindrome equals the overlap with the reverse","body":"Reading a palindrome backward leaves it unchanged, so the longest one is the longest sequence shared, in order, by s and reverse(s)."},{"title":"Match extends the diagonal, mismatch keeps the best","body":"Equal characters write dp[i-1][j-1] + 1; unequal characters write max(dp[i-1][j], dp[i][j-1]). Resetting to 0 would solve the contiguous substring version instead of this subsequence version."},{"title":"One cell per prefix pair: O(n^2)","body":"Filling each of the n^2 prefix pairs once costs O(n^2) time and space, replacing the brute force's roughly 2^n enumeration of subsequences."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
