Skip to content

Longest Palindromic Substring

Medium Day 12 • Striver Blind 75

Given a string s, return the longest palindromic substring in s.

Example 1:

  • Input: s = "babad"
  • Output: "bab"
  • Explanation: “aba” is also a valid answer.

Constraints:

  • 1 <= s.length <= 1000

Expand around center for both odd and even length palindromes.

Expand Around Center


📊 Step-by-Step Execution (Mermaid Diagram)

Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”
graph TD
Problem["Problem of Size N"] --> Sub["Break into Subproblems DP[i]"]
Sub --> Base["Base Cases: DP[0], DP[1]"]
Base --> Trans["State Transition: DP[i] = f(DP[i-1], DP[i-2], ...)"]
Trans --> Table["Fill DP Table / Variables"]
Table --> Result["Return DP[N]"]

function longestPalindrome(s) {
let res = "";
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) { l--; r++; }
if (r - l - 1 > res.length) res = s.substring(l + 1, r);
}
for (let i = 0; i < s.length; i++) {
expand(i, i);
expand(i, i + 1);
}
return res;
}
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
  • Explanation: Expand around center.

function longestPalindrome(s) {
let res = "";
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) { l--; r++; }
if (r - l - 1 > res.length) res = s.substring(l + 1, r);
}
for (let i = 0; i < s.length; i++) {
expand(i, i);
expand(i, i + 1);
}
return res;
}
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
  • Explanation: Expand around all n centers.

  1. Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
  2. Iterate & Evaluate: Process the input according to the boundary conditions.
  3. Update & Return: Compute the optimal answer and return early or at termination.

Treat each character (and pair of characters) as center of a potential palindrome.


  1. Expand outwards from every index i as center.

👉 Solve this problem interactively in the DSA Lab