100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

Longest Palindromic Substring

Find the longest substring that reads the same forwards and backwards using the expand-around-center technique.

String AlgorithmsIntermediate10 min readJul 8, 2026
Analogies

Introduction

A palindrome is a string that reads the same forwards and backwards, such as 'racecar' or 'level'. The longest palindromic substring problem asks for the longest contiguous substring of a given string that is a palindrome. A brute-force check of every substring costs O(n^3), but the expand-around-center technique reduces this to O(n^2) by exploiting the fact that every palindrome is centered at either a single character (odd length) or between two characters (even length).

🏏

Cricket analogy: A scorecard sequence like 'W-1-4-1-W' reading the same forwards and backwards is a palindrome, and finding the longest such symmetric run of overs by checking every possible span costs O(n^3), while expand-around-center exploits that every symmetric run has a single central over or a gap between two overs.

Algorithm/Syntax

python
def longest_palindrome(s: str) -> str:
    if not s:
        return ""

    def expand(left: int, right: int) -> tuple[int, int]:
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        # left/right have overshot by one on each side
        return left + 1, right - 1

    start, end = 0, 0
    for center in range(len(s)):
        l1, r1 = expand(center, center)        # odd-length palindromes
        if r1 - l1 > end - start:
            start, end = l1, r1
        l2, r2 = expand(center, center + 1)     # even-length palindromes
        if r2 - l2 > end - start:
            start, end = l2, r2

    return s[start:end + 1]

Explanation

For each index in the string, the algorithm treats it as a potential center and expands outward in both directions as long as the characters on each side match. There are two kinds of centers: a single character (for odd-length palindromes like 'aba') and a gap between two adjacent characters (for even-length palindromes like 'abba'). By trying both center types at every position and tracking the widest expansion found, the algorithm covers all possible palindromic substrings in O(n) centers x O(n) expansion = O(n^2) time, without needing O(n^3) brute-force substring generation. For truly linear time, Manacher's algorithm can find the longest palindromic substring in O(n) by reusing previously computed palindrome radii, but it is more intricate to implement correctly.

🏏

Cricket analogy: Treating each over as a potential center and expanding outward to check matching scoring patterns on both sides covers odd-length runs like a single big over and even-length runs like two tied overs, in O(n) centers times O(n) expansion, versus Manacher's trickier O(n) reuse of prior symmetry data.

Example

python
s = "babadada"
print(longest_palindrome(s))  # e.g. "adada" (length 5)

# Trace highlights:
# center=1 ('a' in 'bab'): expand -> "bab" (length 3)
# center=4..5 gap in 'adada': expand -> "adada" (length 5), which becomes the new best
# Final answer: the widest palindrome found across all centers, "adada"

Complexity

The expand-around-center approach runs in O(n^2) time in the worst case (e.g., a string of all identical characters, where every expansion runs nearly the full length of the string) and O(1) extra space besides the output. Dynamic programming with a 2D boolean table also solves this problem in O(n^2) time but uses O(n^2) space, making expand-around-center generally preferable. Manacher's algorithm achieves O(n) time and O(n) space by cleverly reusing symmetry information from previously computed palindromes, but the expand-around-center method is usually sufficient and much simpler to reason about and implement correctly in an interview or practical setting.

🏏

Cricket analogy: Expand-around-center runs O(n^2) worst case on a string of near-identical dot balls where every expansion nearly spans the whole innings, uses O(1) extra space, and while a 2D DP table also solves it in O(n^2) time it needs O(n^2) space, so expand-around-center is generally preferred for practical scorecard analysis.

Key Takeaways

  • Every palindrome is centered either at a single character (odd length) or between two characters (even length); checking both cases covers all palindromes.
  • Expand-around-center runs in O(n^2) time and O(1) extra space, much better than the O(n^3) brute-force enumeration of all substrings.
  • A 2D DP table also achieves O(n^2) time but costs O(n^2) space, so expand-around-center is usually preferred.
  • Manacher's algorithm solves the problem in O(n) time by reusing previously computed palindrome information, but is more complex to implement.

Practice what you learned

Was this page helpful?

Topics covered

#Python#AlgorithmsStudyNotes#Algorithms#LongestPalindromicSubstring#Longest#Palindromic#Substring#Algorithm#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse