VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-longest-palindrome-list-linked-list-using-o1-extra-space/

⇱ Longest palindrome in a linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest palindrome in a linked list

Last Updated : 21 May, 2026

Given a linked list, find length of the longest palindrome list that exists in the given linked list.

Examples: 

Input:

👁 2056958075

Output: 5

👁 blobid0_1779102751

Explanation: 2 -> 3 -> 7 -> 3 -> 2 is the linked list whose nodes lead to a palindrome.

Input:

👁 2056958076

Output: 2

👁 blobid1_1779102787

Explanation: 4 -> 4 is the linked list whose nodes lead to a palindrome with length 2.

[Naive Approach] Using Brute Force - O(n^3) Time O(n) Space

The idea is to generate all possible sublists of the linked list and check each sublist for palindrome by copying its elements into an array and comparing from both ends. The maximum length among all palindromic sublists is returned.


Output
5

Time Complexity: O(n^3)
Auxiliary Space: O(n)

[Expected Approach] Using In-place Reversal - O(n^2) Time O(1) Space

The idea is to traverse the linked list and keep reversing it. At each step compare the reversed prefix with the remaining suffix to find palindrome lengths for both odd and even centers.

We iterate through the given a linked list and one by one reverse every prefix of the linked list from the left. After reversing a prefix, we find the longest common list beginning from reversed prefix and the list after the reversed prefix. 


Output
5

Time Complexity: O(n^2)
Auxiliary Space: O(1)

Comment