#5 - Longest Palindromic Substring - Leetcode
Finding the longest palindromic substring is a classic algorithm problem that often shows up in interviews. In this article, we’ll explore different approaches, their time complexities, and why the fastest known solution, Manacher’s Algorithm is still O(n) despite what appears to be nested loops.
✅ Problem Statement
Given a string s, return the longest substring which is a palindrome.
Example:
Input: "babad"
Output: "bab" // or "aba"
🧠 What is a Palindrome?
A palindrome is a string that reads the same backward and forward, like "racecar" or "abba".
🛠️ Approach 1: Brute Force
Try all possible substrings, check each one to see if it’s a palindrome, and keep track of the longest.
⚡️ Approach 2: Expand Around Center (Most Practical)
This clever trick involves expanding around each possible palindrome "center" in the string.
Recommended by LinkedIn
🚀 Approach 3: Manacher’s Algorithm (O(n) Time)
Manacher's Algorithm is the fastest known algorithm for this problem. It preprocesses the input string by inserting separators (#) to treat even and odd length palindromes uniformly.
🔍 Why Manacher’s is O(n) Despite Nested Loops
It looks like we have a for loop with a while inside. So why isn’t it O(n²)?
✅ Because:
This is a classic example where amortized analysis reveals a linear runtime.
🏁 Final Thoughts