5. Longest Palindromic Substring
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the longest substring within a given string s that is a palindrome. A palindrome is a string that reads the same forwards and backwards. For example, "racecar" and "madam" are palindromes. If there are multiple longest palindromic substrings, any of them is a valid answer.
Solution
Longest Palindromic Substring in Python
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return ""
n = len(s)
# start and end indices of the longest palindrome found
start, end = 0, 0
for i in range(n):
# Find length of palindrome with odd length (center at i)
len1 = self._expand_around_center(s, i, i)
# Find length of palindrome with even length (center at i, i+1)
len2 = self._expand_around_center(s, i, i + 1)
max_len = max(len1, len2)
# If a new longest palindrome is found, update start and end
if max_len > end - start:
# The start index is i - (max_len - 1) // 2
start = i - (max_len - 1) // 2
# The end index is i + max_len // 2
end = i + max_len // 2
# Return the longest palindrome using string slicing
return s[start:end+1]
def _expand_around_center(self, s: str, left: int, right: int) -> int:
# Helper method to expand from a center and find palindrome length
L, R = left, right
# Expand as long as we are within bounds and characters match
while L >= 0 and R < len(s) and s[L] == s[R]:
L -= 1
R += 1
# Return the length of the palindrome: R - L - 1
return R - L - 1
Longest Palindromic Substring in Java
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) {
return "";
}
// 'start' and 'end' store the indices of the longest palindrome found so far.
int start = 0;
int end = 0;
for (int i = 0; i < s.length(); i++) {
// Case 1: Odd length palindrome (center is s[i])
int len1 = expandAroundCenter(s, i, i);
// Case 2: Even length palindrome (center is between s[i] and s[i+1])
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
// If we found a palindrome longer than the current longest one
if (len > end - start) {
// Calculate the start and end indices of the new longest palindrome
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
// Return the longest palindromic substring.
// Java's substring method's end index is exclusive.
return s.substring(start, end + 1);
}
// Helper method to find the length of a palindrome by expanding from a center.
private int expandAroundCenter(String s, int left, int right) {
int L = left;
int R = right;
// Expand outwards from the center as long as the characters match and we are within bounds.
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
// The length of the palindrome is the distance between the final R and L pointers.
return R - L - 1;
}
}
Longest Palindromic Substring in C++
class Solution {
public:
string longestPalindrome(string s) {
if (s.length() < 1) {
return "";
}
int start = 0; // Start index of the longest palindrome
int end = 0; // End index of the longest palindrome
for (int i = 0; i < s.length(); i++) {
// Find length of palindrome with odd length, centered at i
int len1 = expandAroundCenter(s, i, i);
// Find length of palindrome with even length, centered at i and i+1
int len2 = expandAroundCenter(s, i, i + 1);
int len = max(len1, len2);
// If a longer palindrome is found, update start and end indices
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
// Return the longest palindromic substring
// C++ substr takes start position and length
return s.substr(start, end - start + 1);
}
private:
// Helper function to expand around a center and find palindrome length
int expandAroundCenter(const string& s, int left, int right) {
int L = left;
int R = right;
// Expand while pointers are valid and characters match
while (L >= 0 && R < s.length() && s[L] == s[R]) {
L--;
R++;
}
// The length of the palindrome is R - L - 1.
// E.g., for "aba", L becomes -1, R becomes 3. Length = 3 - (-1) - 1 = 3.
return R - L - 1;
}
};
Longest Palindromic Substring in TypeScript
function longestPalindrome(s: string): string {
if (s.length < 1) {
return "";
}
// `start` and `end` will store the indices of the longest palindrome found so far.
let start = 0;
let end = 0;
// Helper function to expand around a center and find the length of the palindrome.
const expandAroundCenter = (s: string, left: number, right: number): number => {
let L = left;
let R = right;
// It expands as long as the pointers are within the string bounds and the characters match.
while (L >= 0 && R < s.length && s[L] === s[R]) {
L--;
R++;
}
// Returns the length of the found palindrome.
return R - L - 1;
};
// Iterate through each character of the string to use it as a potential center.
for (let i = 0; i < s.length; i++) {
// Check for odd-length palindromes, with the center at `i`.
const len1 = expandAroundCenter(s, i, i);
// Check for even-length palindromes, with the center between `i` and `i+1`.
const len2 = expandAroundCenter(s, i, i + 1);
// `len` is the maximum length of a palindrome centered at or around `i`.
const len = Math.max(len1, len2);
// If the new palindrome is longer than the previous longest one, update `start` and `end`.
if (len > end - start) {
// Calculate the start index of the new longest palindrome.
start = i - Math.floor((len - 1) / 2);
// Calculate the end index of the new longest palindrome.
end = i + Math.floor(len / 2);
}
}
// Return the longest palindromic substring using the final `start` and `end` indices.
// In TS/JS, substring's second argument is the exclusive end index.
return s.substring(start, end + 1);
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.