Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Suffix Tree Application 6 - Longest Palindromic Substring
Next article icon

Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part 1

Last Updated : 11 Feb, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string, find the longest substring which is palindrome. 

  • if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”
  • if the given string is “abaaba”, the output should be “abaaba”
  • if the given string is “abababa”, the output should be “abababa”
  • if the given string is “abcbabcbabcba”, the output should be “abcbabcbabcba”

We have already discussed Naïve [O(n3)] and quadratic [O(n2)] approaches at Set 1 and Set 2. 
In this article, we will talk about Manacher’s algorithm which finds Longest Palindromic Substring in linear time. 
One way (Set 2) to find a palindrome is to start from the center of the string and compare characters in both directions one by one. If corresponding characters on both sides (left and right of the center) match, then they will make a palindrome. 
Let’s consider string “abababa”. 
Here center of the string is 4th character (with index 3) b. If we match characters in left and right of the center, all characters match and so string “abababa” is a palindrome. 
  

Manacher's Algorithm – Linear Time Longest Palindromic Substring

Here center position is not only the actual string character position but it could be the position between two characters also. 
Consider string “abaaba” of even length. This string is palindrome around the position between 3rd and 4th characters a and a respectively. 
 

Manacher's Algorithm – Linear Time Longest Palindromic Substring

To find Longest Palindromic Substring of a string of length N, one way is take each possible 2*N + 1 centers (the N character positions, N-1 between two character positions and 2 positions at left and right ends), do the character match in both left and right directions at each 2*N+ 1 centers and keep track of LPS. This approach takes O(N^2) time and that’s what we are doing in Set 2. 

Let’s consider two strings “abababa” and “abaaba” as shown below:  

Manacher's Algorithm – Linear Time Longest Palindromic Substring
Manacher's Algorithm – Linear Time Longest Palindromic Substring

In these two strings, left and right side of the center positions (position 7 in 1st string and position 6 in 2nd string) are symmetric. Why? Because the whole string is palindrome around the center position. 
If we need to calculate Longest Palindromic Substring at each 2*N+1 positions from left to right, then palindrome’s symmetric property could help to avoid some of the unnecessary computations (i.e. character comparison). If there is a palindrome of some length L centered at any position P, then we may not need to compare all characters in left and right side at position P+1. We already calculated LPS at positions before P and they can help to avoid some of the comparisons after position P. 
This use of information from previous positions at a later point of time makes the Manacher’s algorithm linear. In Set 2, there is no reuse of previous information and so that is quadratic. 

Manacher’s algorithm is probably considered complex to understand, so here we will discuss it in as detailed way as we can. Some of it’s portions may require multiple reading to understand it properly. 

Let’s look at string “abababa”. In 3rd figure above, 15 center positions are shown. We need to calculate length of longest palindromic string at each of these positions. 

  • At position 0, there is no LPS at all (no character on left side to compare), so length of LPS will be 0.
  • At position 1, LPS is a, so length of LPS will be 1.
  • At position 2, there is no LPS at all (left and right characters a and b don’t match), so length of LPS will be 0.
  • At position 3, LPS is aba, so length of LPS will be 3.
  • At position 4, there is no LPS at all (left and right characters b and a don’t match), so length of LPS will be 0.
  • At position 5, LPS is ababa, so length of LPS will be 5.

…… and so on 

We store all these palindromic lengths in an array, say L. Then string S and LPS Length L look like below:  

Manacher's Algorithm – Linear Time Longest Palindromic Substring

Similarly, LPS Length L of string “abaaba” will look like: 

Manacher's Algorithm – Linear Time Longest Palindromic Substring

In LPS Array L: 

  • LPS length value at odd positions (the actual character positions) will be odd and greater than or equal to 1 (1 will come from the center character itself if nothing else matches in left and right side of it)
  • LPS length value at even positions (the positions between two characters, extreme left and right positions) will be even and greater than or equal to 0 (0 will come when there is no match in left and right side)

Position and index for the string are two different things here. For a given string S of length N, indexes will be from 0 to N-1 (total N indexes) and positions will be from 0 to 2*N (total 2*N+1 positions). 

LPS length value can be interpreted in two ways, one in terms of index and second in terms of position. LPS value d at position I (L[i] = d) tells that: 

  • Substring from position i-d to i+d is a palindrome of length d (in terms of position)
  • Substring from index (i-d)/2 to [(i+d)/2 – 1] is a palindrome of length d (in terms of index)

e.g. in string “abaaba”, L[3] = 3 means substring from position 0 (3-3) to 6 (3+3) is a palindrome which is “aba” of length 3, it also means that substring from index 0 [(3-3)/2] to 2 [(3+3)/2 – 1] is a palindrome which is “aba” of length 3.  

Manacher's Algorithm – Linear Time Longest Palindromic Substring

Now the main task is to compute LPS array efficiently. Once this array is computed, LPS of string S will be centered at position with maximum LPS length value. 
We will see it in Part 2. 



Next Article
Suffix Tree Application 6 - Longest Palindromic Substring

A

Anurag Singh
Improve
Article Tags :
  • Arrays
  • DSA
  • Pattern Searching
  • Strings
  • Microsoft
  • palindrome
Practice Tags :
  • Microsoft
  • Arrays
  • palindrome
  • Pattern Searching
  • Strings

Similar Reads

  • Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
    In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. Here we will implement the same.We have seen that there are no new character comparison needed in case 1 and case 2. In case 3 and case
    15+ min read
  • Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
    In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. In Part 3, we implemented the same. Here we will review the four cases again and try to see it differently and implement the same. All f
    12 min read
  • Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
    In Manacher's Algorithm - Part 1 , we gone through some of the basics and LPS length array. Here we will see how to calculate LPS length array efficiently. To calculate LPS array efficiently, we need to understand how LPS length for any position may relate to LPS length value of any previous already
    11 min read
  • Suffix Tree Application 6 - Longest Palindromic Substring
    Given a string, find the longest substring which is palindrome.We have already discussed Naïve [O(n3)], quadratic [O(n2)] and linear [O(n)] approaches in Set 1, Set 2 and Manacher’s Algorithm. In this article, we will discuss another linear time approach based on suffix tree. If given string is S, t
    15+ min read
  • Longest Palindromic Substring using hashing in O(nlogn)
    Given a string S, The task is to find the longest substring which is a palindrome using hashing in O(N log N) time. Input: S: ”forgeeksskeegfor”, Output: “geeksskeeg” Input: S: ”Geeks”, Output: “ee” Hashing to Solve the Problem:The hashing approach to solving the longest palindromic substring proble
    11 min read
  • Print the longest palindromic prefix of a given string
    Given a string str, the task is to find the longest palindromic prefix of the given string. Examples: Input: str = "abaac" Output: aba Explanation: The longest prefix of the given string which is palindromic is "aba". Input: str = "abacabaxyz" Output: abacaba Explanation: The prefixes of the given s
    12 min read
  • Largest palindromic number by permuting digits
    Given a very large integer n in the form of string, the task is to return the largest palindromic number obtainable by permuting the digits of n. If it is not possible to make a palindromic number, then return an empty string. Examples : Input : "313551"Output : "531135"Explanations : 531135 is the
    10 min read
  • Length of Longest Palindrome Substring
    Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string. Examples: Input: S = "abcbab"Output: 5Explanation: string "abcba" is the longest substring that is a palindrome which is of length 5. Input: S = "abcdaa"Output: 2Explanation: string
    15+ min read
  • Longest palindromic string possible after removal of a substring
    Given a string str, the task is to find the longest palindromic string that can be obtained from it after removing a substring. Examples: Input: str = "abcdefghiedcba" Output: "abcdeiedcba" Explanation: Removal of substring "fgh" leaves the remaining string palindromic Input: str = "abba" Output: "a
    11 min read
  • Rearrange string to obtain Longest Palindromic Substring
    Given string str, the task is to rearrange the given string to obtain the longest palindromic substring. Examples: Input: str = “geeksforgeeks”Output: eegksfskgeeorExplanation: eegksfskgee is the longest palindromic substring after rearranging the string.Therefore, the required output is eegksfskgee
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences