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.

Try It Yourself
redirect icon

[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.

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int x)
    {
        data = x;
        next = nullptr;
    }
};

// Function to check if sublist from start to end is palindrome
bool isPalindrome(Node *start, Node *end)
{
    // Store elements of sublist in vector
    vector<int> temp;

    Node *curr = start;
    while (curr != end->next)
    {
        temp.push_back(curr->data);
        curr = curr->next;
    }

    // Two pointer check for palindrome
    int i = 0, j = temp.size() - 1;
    while (i < j)
    {
        if (temp[i] != temp[j])
            return false;
        i++;
        j--;
    }

    return true;
}

// Function to get length of sublist from start to end
int getLength(Node *start, Node *end)
{
    int len = 0;
    Node *curr = start;

    // Traverse from start to end
    while (curr != end->next)
    {
        len++;
        curr = curr->next;
    }

    return len;
}

// Function to find maximum length palindrome sublist
int maxPalindrome(Node *head)
{
    int res = 0;

    // Fix starting point
    for (Node *i = head; i != nullptr; i = i->next)
    {
        // Fix ending point
        for (Node *j = i; j != nullptr; j = j->next)
        {
            // Check if sublist is palindrome
            if (isPalindrome(i, j))
            {
                int len = getLength(i, j);

                // Update maximum length
                res = max(res, len);
            }
        }
    }

    return res;
}

// Driver Code
int main()
{
    // Creating Linked List: 2->3->7->3->2->12->24
    Node *head = new Node(2);
    head->next = new Node(3);
    head->next->next = new Node(7);
    head->next->next->next = new Node(3);
    head->next->next->next->next = new Node(2);
    head->next->next->next->next->next = new Node(12);
    head->next->next->next->next->next->next = new Node(24);

    cout << maxPalindrome(head);

    return 0;
}
Java
import java.util.ArrayList;

class Node {
  public int data;
  public Node next;

  public Node(int x) {
    data = x;
    next = null;
  }
}

public class GfG {
  public static boolean isPalindrome(Node start, Node end) {
    ArrayList<Integer> temp = new ArrayList<>();

    Node curr = start;
    while (curr!= end.next) {
      temp.add(curr.data);
      curr = curr.next;
    }

    int i = 0, j = temp.size() - 1;
    while (i < j) {
      if (!temp.get(i).equals(temp.get(j)))
        return false;
      i++;
      j--;
    }

    return true;
  }

  public static int getLength(Node start, Node end) {
    int len = 0;
    Node curr = start;

    while (curr!= end.next) {
      len++;
      curr = curr.next;
    }

    return len;
  }

  public static int maxPalindrome(Node head) {
    int res = 0;

    for (Node i = head; i!= null; i = i.next) {
      for (Node j = i; j!= null; j = j.next) {
        if (isPalindrome(i, j)) {
          int len = getLength(i, j);
          res = Math.max(res, len);
        }
      }
    }

    return res;
  }

  public static void main(String[] args) {
    // Creating Linked List: 2->3->7->3->2->12->24
    Node head = new Node(2);
    head.next = new Node(3);
    head.next.next = new Node(7);
    head.next.next.next = new Node(3);
    head.next.next.next.next = new Node(2);
    head.next.next.next.next.next = new Node(12);
    head.next.next.next.next.next.next = new Node(24);

    System.out.println(maxPalindrome(head));
  }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


def isPalindrome(start, end):
    temp = []

    curr = start
    while curr != end.next:
        temp.append(curr.data)
        curr = curr.next

    i = 0
    j = len(temp) - 1
    while i < j:
        if temp[i] != temp[j]:
            return False
        i += 1
        j -= 1

    return True


def getLength(start, end):
    len = 0
    curr = start

    while curr != end.next:
        len += 1
        curr = curr.next

    return len


def maxPalindrome(head):
    res = 0

    i = head
    while i is not None:
        j = i
        while j is not None:
            if isPalindrome(i, j):
                len = getLength(i, j)
                res = max(res, len)
            j = j.next
        i = i.next

    return res


# Driver Code 
if __name__ == "__main__":
    # Creating Linked List: 2->3->7->3->2->12->24
    head = Node(2)
    head.next = Node(3)
    head.next.next = Node(7)
    head.next.next.next = Node(3)
    head.next.next.next.next = Node(2)
    head.next.next.next.next.next = Node(12)
    head.next.next.next.next.next.next = Node(24)

    print(maxPalindrome(head))
C#
using System;
using System.Collections.Generic;

public class Node
{
  public int data;
  public Node next;

  public Node(int x)
  {
    data = x;
    next = null;
  }
}

public class GfG
{
  public static bool IsPalindrome(Node start, Node end)
  {
    List<int> temp = new List<int>();

    Node curr = start;
    while (curr!= end.next)
    {
      temp.Add(curr.data);
      curr = curr.next;
    }

    int i = 0, j = temp.Count - 1;
    while (i < j)
    {
      if (temp[i]!= temp[j])
        return false;
      i++;
      j--;
    }

    return true;
  }

  public static int GetLength(Node start, Node end)
  {
    int len = 0;
    Node curr = start;

    while (curr!= end.next)
    {
      len++;
      curr = curr.next;
    }

    return len;
  }

  public static int MaxPalindrome(Node head)
  {
    int res = 0;

    for (Node i = head; i!= null; i = i.next)
    {
      for (Node j = i; j!= null; j = j.next)
      {
        if (IsPalindrome(i, j))
        {
          int len = GetLength(i, j);
          res = Math.Max(res, len);
        }
      }
    }

    return res;
  }

  public static void Main()
  {
    // Creating Linked List: 2->3->7->3->2->12->24
    Node head = new Node(2);
    head.next = new Node(3);
    head.next.next = new Node(7);
    head.next.next.next = new Node(3);
    head.next.next.next.next = new Node(2);
    head.next.next.next.next.next = new Node(12);
    head.next.next.next.next.next.next = new Node(24);

    Console.WriteLine(MaxPalindrome(head));
  }
}
JavaScript
class Node {
  constructor(x) {
    this.data = x;
    this.next = null;
  }
}

function isPalindrome(start, end) {
  let temp = [];

  let curr = start;
  while (curr!= end.next) {
    temp.push(curr.data);
    curr = curr.next;
  }

  let i = 0, j = temp.length - 1;
  while (i < j) {
    if (temp[i]!== temp[j])
      return false;
    i++;
    j--;
  }

  return true;
}

function getLength(start, end) {
  let len = 0;
  let curr = start;

  while (curr!= end.next) {
    len++;
    curr = curr.next;
  }

  return len;
}

function maxPalindrome(head) {
  let res = 0;

  let i = head;
  while (i!= null) {
    let j = i;
    while (j!= null) {
      if (isPalindrome(i, j)) {
        let len = getLength(i, j);
        res = Math.max(res, len);
      }
      j = j.next;
    }
    i = i.next;
  }

  return res;
}

// Driver Code
// Creating Linked List: 2->3->7->3->2->12->24
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(7);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(12);
head.next.next.next.next.next.next = new Node(24);

console.log(maxPalindrome(head));

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. 

C++
#include <algorithm>
#include <iostream>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int x)
    {
        data = x;
        next = nullptr;
    }
};

// Function to count common nodes in two lists
int countCommon(Node *a, Node *b)
{
    int count = 0;

    // Compare nodes while both lists are valid
    while (a != nullptr && b != nullptr)
    {
        // If data matches, move both pointers
        if (a->data == b->data)
        {
            count++;
            a = a->next;
            b = b->next;
        }
        else
            break;
    }

    return count;
}

// Function to find maximum length palindrome sublist
int maxPalindrome(Node *head)
{
    Node *prev = nullptr;
    Node *curr = head;
    int res = 0;

    // Traverse the list
    while (curr != nullptr)
    {
        Node *next = curr->next;

        // Reverse current node
        curr->next = prev;

        // Check for odd length palindrome (center at curr)
        int oddLen = 2 * countCommon(prev, next) + 1;

        // Check for even length palindrome (center between prev and curr)
        int evenLen = 2 * countCommon(curr, next);

        // Update maximum length
        res = max(res, max(oddLen, evenLen));

        // Move pointers forward
        prev = curr;
        curr = next;
    }

    return res;
}

// Driver Code
int main()
{
    Node *head = new Node(2);
    head->next = new Node(3);
    head->next->next = new Node(7);
    head->next->next->next = new Node(3);
    head->next->next->next->next = new Node(2);
    head->next->next->next->next->next = new Node(12);
    head->next->next->next->next->next->next = new Node(24);

    cout << maxPalindrome(head);

    return 0;
}
Java
import java.util.*;

class Node {
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to count common nodes in two lists
    public int countCommon(Node a, Node b)
    {
        int count = 0;

        // Traverse both lists while nodes match
        while (a != null && b != null) {
            if (a.data == b.data) {
                count++;
                a = a.next;
                b = b.next;
            }
            else
                break;
        }

        return count;
    }

    // Function to find maximum length palindrome sublist
    public int maxPalindrome(Node head)
    {
        Node prev = null;
        Node curr = head;
        int res = 0;

        // Traverse list and reverse progressively
        while (curr != null) {
            Node next = curr.next;

            // Reverse current node
            curr.next = prev;

            // Odd length palindrome (center at curr)
            int oddLen = 2 * countCommon(prev, next) + 1;

            // Even length palindrome (center between nodes)
            int evenLen = 2 * countCommon(curr, next);

            // Update result
            res = Math.max(res, Math.max(oddLen, evenLen));

            // Move pointers
            prev = curr;
            curr = next;
        }

        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(7);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.next = new Node(12);
        head.next.next.next.next.next.next = new Node(24);

        System.out.println(
            new GfG().maxPalindrome(head));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to count common nodes in two lists
def countCommon(a, b):
    count = 0

    # Compare nodes while both lists are valid
    while a is not None and b is not None:
        # If data matches, move both pointers
        if a.data == b.data:
            count += 1
            a = a.next
            b = b.next
        else:
            break

    return count

# Function to find maximum length palindrome sublist
def maxPalindrome(head):
    prev = None
    curr = head
    res = 0

    # Traverse the list
    while curr is not None:
        next = curr.next

        # Reverse current node
        curr.next = prev

        # Check for odd length palindrome (center at curr)
        oddLen = 2 * countCommon(prev, next) + 1

        # Check for even length palindrome (center between prev and curr)
        evenLen = 2 * countCommon(curr, next)

        # Update maximum length
        res = max(res, max(oddLen, evenLen))

        # Move pointers forward
        prev = curr
        curr = next

    return res

# Driver Code
if __name__ == '__main__':
    head = Node(2)
    head.next = Node(3)
    head.next.next = Node(7)
    head.next.next.next = Node(3)
    head.next.next.next.next = Node(2)
    head.next.next.next.next.next = Node(12)
    head.next.next.next.next.next.next = Node(24)

    print(maxPalindrome(head))
C#
using System;

public class Node {
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class GfG {

    // Function to count common nodes in two lists
    public int CountCommon(Node a, Node b)
    {
        int count = 0;

        // Traverse both lists while nodes match
        while (a != null && b != null) {
            if (a.data == b.data) {
                count++;
                a = a.next;
                b = b.next;
            }
            else
                break;
        }

        return count;
    }

    // Function to find maximum length palindrome sublist
    public int MaxPalindrome(Node head)
    {
        Node prev = null;
        Node curr = head;
        int res = 0;

        // Traverse list and reverse progressively
        while (curr != null) {
            Node next = curr.next;

            // Reverse current node
            curr.next = prev;

            // Odd length palindrome (center at curr)
            int oddLen = 2 * CountCommon(prev, next) + 1;

            // Even length palindrome (center between nodes)
            int evenLen = 2 * CountCommon(curr, next);

            // Update result
            res = Math.Max(res, Math.Max(oddLen, evenLen));

            // Move pointers
            prev = curr;
            curr = next;
        }

        return res;
    }

    // Driver Code
    public static void Main(string[] args)
    {
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(7);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.next = new Node(12);
        head.next.next.next.next.next.next = new Node(24);

        Console.WriteLine(new GfG().MaxPalindrome(head));
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function to count common nodes in two lists
function countCommon(a, b) {
    let count = 0;

    // Compare nodes while both lists are valid
    while (a!== null && b!== null) {
        // If data matches, move both pointers
        if (a.data === b.data) {
            count++;
            a = a.next;
            b = b.next;
        } else {
            break;
        }
    }

    return count;
}

// Function to find maximum length palindrome sublist
function maxPalindrome(head) {
    let prev = null;
    let curr = head;
    let res = 0;

    // Traverse the list
    while (curr!== null) {
        let next = curr.next;

        // Reverse current node
        curr.next = prev;

        // Check for odd length palindrome (center at curr)
        let oddLen = 2 * countCommon(prev, next) + 1;

        // Check for even length palindrome (center between prev and curr)
        let evenLen = 2 * countCommon(curr, next);

        // Update maximum length
        res = Math.max(res, Math.max(oddLen, evenLen));

        // Move pointers forward
        prev = curr;
        curr = next;
    }

    return res;
}

// Driver Code
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(7);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(12);
head.next.next.next.next.next.next = new Node(24);

console.log(maxPalindrome(head));

Output
5

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

Comment