5. Longest Palindromic Substring
Asked at 65Microsoft80Bloomberg79Amazon79Google69Meta68Apple46Tinkoff94tcs92Cognizant85Adobe82IBM75Visa72Infosys70Yandex70Goldman Sachs45Nielsen100HSBC92Cisco91ZS Associates88Disney88DP world88Wix87SAP87PornHub87EarnIn84Softwire80PhonePe78athenahealth78BitGo77EPAM Systems77Deloitte75HashedIn72Commvault71eBay71Autodesk69persistent systems69Shopee69opentext67Huawei67Walmart Labs66Grab66Zoho65TikTok65Turing64Accolite64Oracle64Tekion63Swiggy59Pure Storage59Epic Systems59ServiceNow55Morgan Stanley54Accenture54Flipkart52Palo Alto Networks50josh technology50Salesforce49Zopsmart49Citadel47PayPal42Uber40Nvidia39Capital One35DoorDash29LinkedIn20
Problem
Return the longest substring of s that is a palindrome (any one of them if there are ties).
Example: "babad" → "bab" (or "aba"); "cbbd" → "bb"
Constraints: length ≤ 1000.
Every palindrome has a centre (a char or a gap between chars: 2n−1 centres). Expand outward from each while ends match; keep the longest.
b a b a d
^ centre 'a' -> "bab"(1..3) -> expand fails at d
Complexity: O(n²) time, O(1) space (Manacher's is O(n)).
class Solution:
def longestPalindrome(self, s: str) -> str:
best = (0, 0)
for c in range(2 * len(s) - 1):
l, r = c // 2, (c + 1) // 2
while l >= 0 and r < len(s) and s[l] == s[r]:
l, r = l - 1, r + 1
if r - l - 1 > best[1] - best[0]:
best = (l + 1, r)
return s[best[0]:best[1]]
assert Solution().longestPalindrome("babad") in ("bab", "aba")
assert Solution().longestPalindrome("cbbd") == "bb"
assert Solution().longestPalindrome("a") == "a"
class Solution {
public String longestPalindrome(String s) {
int bl = 0, br = 0;
for (int c = 0; c < 2 * s.length() - 1; c++) {
int l = c / 2, r = (c + 1) / 2;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
if (r - l - 1 > br - bl) { bl = l + 1; br = r; }
}
return s.substring(bl, br);
}
}
func longestPalindrome(s string) string {
lo, hi := 0, 0 // best is s[lo:hi]
for c := 0; c < 2*len(s)-1; c++ { // 2n-1 centres: characters and gaps
l, r := c/2, (c+1)/2
for l >= 0 && r < len(s) && s[l] == s[r] {
l, r = l-1, r+1
}
if r-l-1 > hi-lo {
lo, hi = l+1, r
}
}
return s[lo:hi]
}