Skip to the solution
MediumDSA9 min read

How do you find the longest palindromic substring?

109 views

The problem

Question presented to candidate: "Given a string, return the longest substring that is a palindrome. For example, babad gives bab or aba, and cbbd gives bb. Please write it in Python, and tell me the time and space cost."

What a strong answer should cover:

  • Every palindrome has a centre: n character centres and n - 1 gap centres; expand two pointers outward from each while the characters match.
  • Track the best (start, length) and slice once at the end; O(n^2) time, O(1) extra space.
  • The O(n^3) brute force and the O(n^2)-space DP as alternatives; Manacher as the O(n) follow-up.
  • Edge cases: empty string, single character, even-length palindromes, ties.
  • Python specifics: slicing (s[a:b]) copies, so do not slice inside the loop; [[False] * n] * n aliases one row n times; Python loops are slow enough that the O(n^3) brute force is unusable beyond a few hundred characters.

Clarifying questions expected:

  • "Substring or subsequence?"
  • "If there is a tie, which palindrome should I return?"

Code / implementation expected: Yes โ€” longest_palindrome(s) in Python using expand-around-centre with index pointers.

  • strings
  • dp
  • expand-center

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonExpand around centre on normal and edge-case strings
PythonBrute force, DP, expand and Manacher agree, with work counters

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 125 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you check if an array can be partitioned into two equal-sum subsets?

Continue