codejump
MediumPythonJavaScriptTypeScript

DP — Longest Palindromic Substring

AlgorithmsDynamic ProgrammingStrings

solve(s) — return the longest substring of s that reads the same forwards and
backwards. If several have the maximum length, return the one that **starts
first**.

Every palindrome is centred on a character (odd length) or between two characters
(even length), so try each of the 2n - 1 centres and expand outwards while the
two ends match. That is O(n²) time and O(1) space — better than the DP table.

Examples

solve("babad")             → "bab"    // "aba" has the same length but starts later
solve("cbbd")              → "bb"
solve("a")                 → "a"
solve("forgeeksskeegfor")  → "geeksskeeg"

Sample tests

Test #1Tie — earliest start wins
Input: ["babad"]
Output: "bab"
Test #2Even-length palindrome
Input: ["cbbd"]
Output: "bb"
Test #3Single character
Input: ["a"]
Output: "a"