intermediate9 min read·Updated October 7, 2026

Longest Palindromic Substring Explained: Tracing 'cbbd' & 'babad'

Master the Longest Palindromic Substring problem. Walk through the center expansion model using 'cbbd' and 'babad', complete with time complexity and edge cases.

By Learnisim AI·Published October 7, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
  • Basic string indexing and slicing in any programming language
Longest Palindromic Substring: Center Expansion Model Finding max palindromes in "cbbd" and "babad" without redundant slicing 1. The Substring Trap (Why Slicing Fails) • Naive check: generate all n(n+1)/2 substrings • For length 1,000 → ~500,000 candidates • Wastes CPU cycles re-checking overlapping regions a aba ababa (Redundant) O(N³) time 2. Center Expansion Model (Inside Out) • Every palindrome expands around a center • Centers are single chars (odd len) or gaps (even len) • Expand outward while left == right characters c Expand Left & Right O(N²) 3. Tracing "c b b d" (Even Length Center) Indices: 0('c'), 1('b'), 2('b'), 3('d') c 0 b 1 b 2 d 3 Center (1, 2) 1. Test center gap between index 1 & 2 ('b' & 'b') 2. Match! Expand left to 'c' (0) and right to 'd' (3) Result: Longest Palindromic Substring = "bb" (Len 2) 4. Tracing "b a b a d" (Odd Length Center) Indices: 0('b'), 1('a'), 2('b'), 3('a'), 4('d') b 0 a 1 b 2 a 3 d 4 Center (2) 1. Center at index 2 ('b'); expand outwards 2. Left at index 1 ('a') matches right at index 3 ('a') Result: Longest Palindromic Substring = "bab" (or "aba")
Longest palindrome in "cbbd" and in "babad" overview diagram
Why

Why simple string slicing fails for finding the longest palindromic substring

Phase 1: The Substring Trap

Imagine you are handed the string s = "cbbd". Your goal is to find the longest contiguous block of characters that reads the exact same forwards and backwards. For s = "cbbd", that target is bb. For s = "babad", it is either bab or aba. It sounds simple: why not just generate every possible substring, check if it is a palindrome, and keep the longest one?
If a string has length , there are roughly unique substrings. For a tiny string like babad (), that is 15 candidates. But scale that up to a modest 1,000-character string, and you are suddenly inspecting nearly 500,000 substrings. Checking each one by reversing it takes extra work, pushing a naive brute-force approach to a sluggish runtime. Worse, you waste endless CPU cycles re-checking overlapping regions like aba inside ababa from scratch.
We need a method that avoids redundant checks and zeroes in on the true longest palindromic substring without generating every useless fragment.
Longest Palindromic Substring: Why Naive Slicing Fails Contiguous substring vs. explosive candidate growth & center-expansion solution Phase 1: Contiguous Targets s = "cbbd" → Target: c b b d Palindrome: "bb" s = "babad" → Target: b a b a d Palindrome: "bab" Phase 2: The Substring Trap (Brute Force) Formula: ~ n(n + 1) / 2 candidates! Length 5 ("babad") → 15 subs Length 1,000 → ~500,000 subs Redundancy Issue: Re-checking overlapping regions like "aba" inside "ababa" from scratch wastes CPU cycles. Phase 3: The Center-Expansion Solution (Optimal Approach) Instead of generating useless fragments, anchor on every possible center and expand outward! String: b a b a d b a b Center a d Expand Outward ('a' == 'a') 2 Kinds of Centers • Odd length: anchored on 1 char • Even length: anchored between two chars (e.g., "bb") Complexity Win • Time: O(n²) worst-case • Space: O(1) auxiliary No extra substring copies! Note: Substrings must be contiguous (e.g., "b-a-d" is a subsequence, not a valid substring target).
Why simple string slicing fails for finding the longest palindromic substring diagram
Model

The Center Expansion Model: Viewing Palindromes from the Inside Out

Phase 2: The Center Expansion Model

When we looked at finding the longest palindromic substring in our working examples like cbbd and babad, checking every possible start and end index brute-style led to an explosion of redundant checks. Instead of hunting from the outside in, we flip our perspective to look at expansion around centers. Every palindrome is guaranteed to have a precise middle point. For a string of length , how many such middle points exist?
Think about the possible axes of symmetry in cbbd. A palindrome can have an odd length (anchored on a single exact character like the first b in cbbd) or an even length (anchored strictly between two adjacent characters like the double bb in cbbd). If we test every single index as an odd-length center and every gap between and as an even-length center , we cover every possible palindrome topology without missing a single configuration.
To see this mapped to our working data, consider index 1 in cbbd (the first b). If we treat it as an odd center, our left and right pointers both start at index 1. Inspecting outwards: s[1] matches s[1] (b equals b), but expanding further left hits s[0] (c) and right hits s[2] (b), so c != b and the expansion stops. But what about the even center between index 1 and index 2 (bb)? Here, left starts at 1 (b) and right starts at 2 (b). They match! Expanding outward from there fails, yielding our candidate substring bb of length 2.
By treating the string as a sequence of potential centers ( single-character centers and dual-character gaps), we transform a chaotic search space into a systematic sweep. We only expand outward as long as our boundary characters match, recording the maximum length and bounds whenever we beat our previous record.
Center Expansion Model: Viewing Palindromes from the Inside Out 1. Odd-Length Center (Single Character) Example: s = "babad" | Center at index 2 ('b') b 0 a 1 b 2 (Cntr) a 3 d 4 s[1]==s[3] s[0]!=s[4] (stop) Max Palindrome: "bab" (len 3) 2. Even-Length Center (Between Indices) Example: s = "cbbd" | Center between 1 and 2 c 0 b 1 b 2 d 3 Gap Center s[1]==s[2] (bb) s[0]!=s[3] (stop) Max Palindrome: "bb" (len 2) Why Center Expansion Beats Brute Force 1. Complete Topology For string length N, there are N odd centers & (N-1) even gaps. Zero palindromes are missed! Exhaustive & elegant coverage 2. Linear Growth Check From each center, push pointers left (L--) and right (R++) outward while s[L] == s[R] matches. Stops immediately on mismatch 3. O(N²) Time Efficiency Avoids redundant O(N³) checks of every substring combination. Achieves optimal O(1) space. Industry standard interview approach
The Center Expansion Model: Viewing Palindromes from the Inside Out diagram
Worked example

Tracing Center Expansion Step by Step on C-B-B-D

Phase 3:

Let us trace the center expansion algorithm on our working example string s = "cbbd". Our goal is to find any longest palindromic substring by testing every possible center.

Given

String s = "cbbd" of length 4. We maintain two variables for our best result: start = 0 and maxLength = 1, representing the slice s[0:1] ("c") as our initial best palindrome.

Steps

We loop through each index i from 0 to 3, checking both odd-length and even-length centers:
1. Index i = 0 (character 'c'):
- Odd center (0, 0): Left and right start at index 0 (s[0] == 'c'). Expand left and right while bounds hold and characters match. No expansion possible. Length = 1. Best remains "c" (length 1).
- Even center (0, 1): Left = 0 ('c'), Right = 1 ('b'). Since s[0] != s[1], expansion fails immediately. Length = 0.
2. Index i = 1 (character 'b'):
- Odd center (1, 1): Left = 1 ('b'), Right = 1 ('b'). Expand: check s[0] ('c') and s[2] ('b'). They do not match ('c' != 'b'). Length = 1. Best remains length 1.
- Even center (1, 2): Left = 1 ('b'), Right = 2 ('b'). Since s[1] == s[2], palindrome "bb" is valid! Expand further: Left = 0 ('c'), Right = 3 ('d'). s[0] != s[3], so expansion stops. Length = . Since , update start = 1 and maxLength = 2.
3. Index i = 2 (character 'b'):
- Odd center (2, 2): Left = 2 ('b'), Right = 2 ('b'). Expand: Left = 1 ('b'), Right = 3 ('d'). s[1] != s[3]. Length = 1. Best remains length 2.
- Even center (2, 3): Left = 2 ('b'), Right = 3 ('d'). s[2] != s[3]. Length = 0.
4. Index i = 3 (character 'd'):
- Odd center (3, 3): Single character 'd'. Length = 1.
- Even center (3, 4): Out of bounds.

Result

The search completes. The final best slice corresponds to start = 1 and maxLength = 2, extracting s[1:3], which yields the expected result: "bb".
Try this: Trace the center expansion algorithm manually for s = "babad". List the center indices (both odd and even) that successfully yield the longest palindromic substring "bab" or "aba".
Center Expansion: Tracing s = "cbbd" (Index i = 1, Even Center) idx 0 c idx 1 (L) b idx 2 (R) b idx 3 d s[1] == s[2] ("bb") s[0] != s[3] (mismatch!) Phase 3: Even-Length Center Test at Index i = 1 Initialize Even Center: Left = 1 ("b"), Right = 2 ("b"). First Expansion: s[1] == s[2] matches! Valid palindrome substring "bb" found. Second Expansion: Left = 0 ("c"), Right = 3 ("d"). Mismatch ('c' != 'd'), expansion stops. Result: Length 2 > maxLength (1). Update start = 1 and maxLength = 2.
Tracing Center Expansion Step by Step on C-B-B-D diagram
Practice

Test Your Center Expansion Mechanics on B-A-B-A-D

Phase 4:

Now it is time to put the center expansion model to work on our second canonical input: s = "babad". Recall that in the previous phase, we traced s = "cbbd" and found that the even center between indices 1 and 2 yielded bb. Here, you will trace s = "babad" yourself to see how odd and even centers compete and why both lengths can appear as valid answers.
Take out a notepad or trace mentally through every center index from i = 0 to i = n - 1. Check both odd expansions (where left and right start at i) and even expansions (where left starts at i and right starts at i + 1). Keep a running tracker of the longest valid palindromic substring found so far, updating your best start and end indices whenever an expansion exceeds the previous maximum length.

The Task

Given the string s = "babad", determine the final longest palindromic substring recorded by the center expansion algorithm after checking all possible centers.
Question:
When running the center expansion algorithm on s = "babad", what are the lengths and starting positions of the palindromes discovered at center index i = 1 (odd center b at index 1) and the even center between index 1 (a) and index 2 (b), and which substring is ultimately returned as the final answer?
python
def longestPalindrome(s: str) -> str:
    # Implement or trace center expansion for s = "babad"
    pass
Apply

Transferring Center Expansion to Overlapping and Alternating Structures

Phase 5: Transfer

Now that we have traced cbbd to find bb and validated babad to find bab or aba, we can examine how this exact center-expansion pattern transfers to more challenging variations. Consider a string entirely composed of identical characters like aaaa, or a string with alternating patterns where every single-character and two-character center could potentially expand across the entire length. In aaaa, the center at index 1 expands outward through indices (1,2), then (0,3), immediately yielding length 4 (aaaa). The fundamental rule remains identical: every index acts as a dual anchor for odd and even expansions. However, the runtime behavior changes because maximum possible overlaps cause the inner loops to run closer to their theoretical limit per center instead of terminating early on mismatching characters like d in cbbd.
When you encounter new substring or subsegment problems where solutions mirror around a pivot—such as finding palindromic partitions or counting substring symmetries—do not rebuild a fresh brute-force validator. Instead, check whether your state space can be decomposed into discrete centers. If a structure allows left-right boundary checks that grow monotonically outward, center expansion transfers directly with zero extra space overhead.
python
def longest_palindrome_transfer(s: str) -> str:
    # Apply the center expansion template learned from 'cbbd' and 'babad'
    # to a new variation, e.g., handling strings with all identical characters.
    pass

FAQ

What is the result of finding the longest palindromic substring in 'cbbd'?
For the string 'cbbd', the longest palindromic substring is 'bb', found by expanding outwards from the center between the two adjacent 'b' characters.
Why does simple string slicing fail for this problem?
Generating all possible substrings takes O(n^2) space and checking each one for palindromic symmetry takes O(n) time, leading to an inefficient O(n^3) brute-force approach.
What is the time and space complexity of the center expansion approach?
Center expansion runs in O(n^2) time in the worst case (since there are 2n-1 possible centers) and uses O(1) auxiliary space.
How do you handle both odd and even length palindromes?
You must check centers of length 1 (single character, for odd-length palindromes like 'aba') and centers of length 2 (between two characters, for even-length palindromes like 'bb').

Keep learning