In this tutorial, we’ll learn how to find the longest palindromic substring in a given string using Java. This is a famous interview question asked by companies like Google, Amazon, and Microsoft.
🧠What is a Palindromic Substring?
A palindrome is a string that reads the same backward as forward. A palindromic substring is a part of the string that is also a palindrome.
📌 Example
Input: "babad" Output: "bab" or "aba" Input: "cbbd" Output: "bb"
✅ Java Program (Expand Around Center Approach)
public class LongestPalindrome {
public static void main(String[] args) {
String input = "babad";
String result = longestPalindrome(input);
System.out.println("Longest Palindromic Substring: " + result);
}
static String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandFromMiddle(s, i, i); // Odd length
int len2 = expandFromMiddle(s, i, i + 1); // Even length
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
static int expandFromMiddle(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}
✅ Output
Longest Palindromic Substring: bab
💡 Interview Tip
This method runs in O(n^2)
time and uses O(1)
space. You might also be asked to implement it using dynamic programming, which uses extra space but follows a tabulation-based approach.
📚 Conclusion
We explored how to find the longest palindromic substring using the expand-around-center technique in Java. This problem is a favorite in coding interviews and helps sharpen your understanding of string manipulation and two-pointer techniques.