VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solution-longest-palindrome/

⇱ CSES Solution - Longest Palindrome - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solution - Longest Palindrome

Last Updated : 23 Jul, 2025

Prerequisite:Manacher’s Algorithm

Given a string, your task is to determine the longest palindromic substring of the string. For example, the longest palindrome in aybabtu is bab.

Example:

Input: s = aybabtu
Output: bab

Input: GeeksgfgGeeks
Output: gfg

Approach:

The idea is to use Manacher’s algorithm, which is a linear time complexity algorithm for finding the longest palindromic substring in a given string.

Lets break down the intuition into some steps:

  • We'll use two arrays, oddLength[] and evenLength[], to store the lengths of the longest odd-length and even-length palindromic substrings centered at each index of the input string.
  • Odd-Length Palindromes: First calculates the longest odd-length palindromic substring centered at each index. It uses a variable length to keep track of the current length of the palindrome. It starts from the center and expands in both directions (left and right) until it finds a mismatch or reaches the boundary of the string. The left and right variables are used to keep track of the boundaries of the current longest palindrome.
  • Even-Length Palindromes: The process is repeated for even-length palindromes. The only difference is that the initial length is set to 0 and the expansion starts from one position to the left of the center.
  • Finding the Longest Palindrome: After the lengths of all palindromic substrings are calculated, iterates over the oddLength and evenLength arrays to find the maximum length and the center of the longest palindromic substring.
  • Finally, the longest palindromic substring is extracted from the input string using the substr function and returned.

Steps-by-step approach:

  • Two arrays oddLength[] and evenLength[] are declared to store the lengths of the longest palindromic substrings centered at each index.
  • Implement solve() function:
    • Iterates through the string to find the longest palindromic substring using Manacher's algorithm.
    • For each index i, it calculates the length of the longest odd-length palindromic substring centered at that index.
    • Then calculates the length of the longest even-length palindromic substring centered at each index.
    • Updates the lengths of palindromic substrings in the oddLength and evenLength arrays.
    • Returns the longest palindromic substring found in the input string

Below are the implementation of the above approach:


Output
gfg

Time Complexity: O(n), where n is the length of given string
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: