Longest palindrome in a string
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Finding the longest palindromic substring is a classic interview and production coding problem. The brute-force approach is simple but slow for long strings. A center-expansion algorithm gives strong performance with straightforward implementation.
Understand the Core Idea
A palindrome reads the same forward and backward. Every palindrome has a center, either one character for odd length or a gap between two characters for even length. Expand from each center while characters match.
This avoids testing every possible substring directly.
Efficient Center Expansion Implementation
The following Python function runs in quadratic time and constant extra space.
This solution balances clarity and performance for most practical inputs.
Testing with Representative Cases
Always validate both odd and even palindrome cases, plus empty and single-character input.
For ambiguous outputs like babad, aba is also valid. Length checks are often more robust than exact string checks.
Complexity and Alternatives
Center expansion runs in quadratic time and constant extra space. For very large strings where performance is critical, Manacher algorithm achieves linear time but is harder to implement and maintain.
In production, center expansion is often the best tradeoff unless profiling proves otherwise.
Dynamic Programming Alternative
Another common method uses dynamic programming to mark whether s[i:j] is a palindrome. It is easier to reason about for some developers, though it uses more memory.
This approach is useful for educational contexts and for verifying center-expansion implementations.
Benchmarking Different Approaches
Benchmarking helps choose implementation based on input size and runtime constraints.
Real measurements often show center expansion as the best balance for typical workloads.
Production Considerations
If this function is used in user-facing APIs, add input size guards and timeout strategy for very large strings. Document complexity and expected behavior for ambiguous outputs. Clear contracts reduce debugging overhead later.
Common Pitfalls
- Handling only odd-length centers and missing even-length palindromes.
- Returning indices incorrectly after expansion loop exits.
- Using full substring reversal checks in nested loops and creating cubic time behavior.
- Writing tests that assume one unique answer when multiple valid outputs exist.
Summary
- Expand around each character and each gap to find palindromes efficiently.
- Track best left and right indices during iteration.
- Test odd and even cases to avoid edge-case bugs.
- Use linear-time alternatives only when proven necessary.

