Expand Around Center is a useful problem-solving technique for problems where we need to explore values symmetrically from a central position.
The basic idea is simple:
Start from a possible center and expand toward both sides while checking a condition.
One common example where this technique is useful is Longest Palindromic Substring.
What does "Expand Around Center" mean?
Imagine this palindrome:
b a b
↑
center
The center is a.
We start there and expand toward both sides:
b [a] b
↑ ↑
We compare the characters on both sides.
Since b === b, we can continue expanding.
This works particularly well for problems involving palindromes, because a palindrome is symmetric around its center.
Example: Longest Palindromic Substring
For:
s = "babad"
One possible palindrome is:
b a b
↑
center
Starting from the center, we compare the characters outward.
b [a] b
↑ ↑
Both characters match, so "bab" is a palindrome.
But there is another possibility:
a b a
↑
center
So we need to check different possible centers in the string.
There are two types of centers
1. Odd-length palindrome
For example:
"aba"
a
↑
center
The center is a single character.
In code:
expand(i, i)
2. Even-length palindrome
For example:
"abba"
b b
↑ ↑
center
Here, the center is between two characters.
In code:
expand(i, i + 1)
So for every index, we check both possibilities:
expand(i, i); // Odd-length palindrome
expand(i, i + 1); // Even-length palindrome
The basic pattern
The complete thought process is:
Choose a possible center
↓
Expand to the left and right
↓
Compare both values
↓
If they satisfy the condition
↓
Continue expanding
For the Longest Palindromic Substring problem, we keep track of the longest palindrome we find.
Simple JavaScript implementation
var longestPalindrome = function(s) {
let ans = "";
const expand = (l, r) => {
while (
l >= 0 &&
r < s.length &&
s[l] === s[r]
) {
l--;
r++;
}
if (r - l - 1 > ans.length) {
ans = s.slice(l + 1, r);
}
};
for (let i = 0; i < s.length; i++) {
expand(i, i); // Odd
expand(i, i + 1); // Even
}
return ans;
};
Expand Around Center vs Two Pointers
They may look similar because both use two indexes, but the idea is different.
Two Pointers
→ ←
Two pointers move according to the problem's conditions.
Expand Around Center
← center →
We start from a possible center and expand symmetrically outward.
Complexity
For each position, we may expand across the string.
-
Time:
O(n²) -
Space:
O(1)
For the constraint n <= 1000, this approach works well.
My takeaway
The most important thing I learned wasn't the code itself.
It was recognizing the pattern:
Palindrome → symmetry → possible center → expand outward
Once I understood that, the problem became much easier to approach.
I'll be adding more DSA patterns to this series as I learn them.
Top comments (0)