Skip to main content

13. Longest Palindromic Substring

mediumAsked at Swiggy

Return the longest substring of s that reads the same forwards and backwards.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s of length n, return the longest palindromic substring contained in s. If multiple have the same maximum length, return any one.

Constraints

  • 1 <= s.length <= 1000
  • s contains only printable ASCII

Examples

Example 1

Input
s='babad'
Output
'bab' or 'aba'

Example 2

Input
s='cbbd'
Output
'bb'

Approaches

1. Brute substring check

Test every substring for palindrome property.

Time
O(n^3)
Space
O(1)
function isPal(t){return t===t.split('').reverse().join('');}
let best='';
for (let i=0;i<s.length;i++)
  for (let j=i+1;j<=s.length;j++)
    if (isPal(s.slice(i,j)) && j-i>best.length) best=s.slice(i,j);
return best;

Tradeoff:

2. Expand around centers

Every palindrome has a center (single char or gap between two chars). For each of the 2n-1 centers, expand outward while characters match; track the best span.

Time
O(n^2)
Space
O(1)
function longestPalindrome(s) {
  let start = 0, end = 0;
  const expand = (l, r) => {
    while (l >= 0 && r < s.length && s[l] === s[r]) { l--; r++; }
    return [l + 1, r - 1];
  };
  for (let i = 0; i < s.length; i++) {
    for (const [l, r] of [expand(i, i), expand(i, i + 1)]) {
      if (r - l > end - start) { start = l; end = r; }
    }
  }
  return s.slice(start, end + 1);
}

Tradeoff:

Swiggy-specific tips

Swiggy treats this as a 'comfort with two-pointer expansion' check that maps onto symmetric route validation in their restaurant-graph problems.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Longest Palindromic Substring and other Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →