Length of longest palindrome list in a linked list using O(1) extra space
Last Updated :
06 Apr, 2023
Given a linked list, find the length of the longest palindrome list that exists in that linked list.
Examples:
Input : List = 2->3->7->3->2->12->24
Output : 5
The longest palindrome list is 2->3->7->3->2
Input : List = 12->4->4->3->14
Output : 2
The longest palindrome list is 4->4
A simple solution could be to copy linked list content to array and then find the longest palindromic subarray in the array, but this solution is not allowed as it requires extra space.
The idea is based on iterative linked list reverse process. 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.
Below is the implementation of the above idea.
C++
// C++ program to find longest palindrome
// sublist in a list in O(1) time.
#include<bits/stdc++.h>
using namespace std;
//structure of the linked list
struct Node
{
int data;
struct Node* next;
};
// function for counting the common elements
int countCommon(Node *a, Node *b)
{
int count = 0;
// loop to count common in the list starting
// from node a and b
for (; a && b; a = a->next, b = b->next)
// increment the count for same values
if (a->data == b->data)
++count;
else
break;
return count;
}
// Returns length of the longest palindrome
// sublist in given list
int maxPalindrome(Node *head)
{
int result = 0;
Node *prev = NULL, *curr = head;
// loop till the end of the linked list
while (curr)
{
// The sublist from head to current
// reversed.
Node *next = curr->next;
curr->next = prev;
// check for odd length palindrome
// by finding longest common list elements
// beginning from prev and from next (We
// exclude curr)
result = max(result,
2*countCommon(prev, next)+1);
// check for even length palindrome
// by finding longest common list elements
// beginning from curr and from next
result = max(result,
2*countCommon(curr, next));
// update prev and curr for next iteration
prev = curr;
curr = next;
}
return result;
}
// Utility function to create a new list node
Node *newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
/* Driver program to test above functions*/
int main()
{
/* Let us create a linked lists to test
the functions
Created list is a: 2->4->3->4->2->15 */
Node *head = newNode(2);
head->next = newNode(4);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(2);
head->next->next->next->next->next = newNode(15);
cout << maxPalindrome(head) << endl;
return 0;
}
Java
// Java program to find longest palindrome
// sublist in a list in O(1) time.
class GfG
{
//structure of the linked list
static class Node
{
int data;
Node next;
}
// function for counting the common elements
static int countCommon(Node a, Node b)
{
int count = 0;
// loop to count common in the list starting
// from node a and b
for (; a != null && b != null;
a = a.next, b = b.next)
// increment the count for same values
if (a.data == b.data)
++count;
else
break;
return count;
}
// Returns length of the longest palindrome
// sublist in given list
static int maxPalindrome(Node head)
{
int result = 0;
Node prev = null, curr = head;
// loop till the end of the linked list
while (curr != null)
{
// The sublist from head to current
// reversed.
Node next = curr.next;
curr.next = prev;
// check for odd length
// palindrome by finding
// longest common list elements
// beginning from prev and
// from next (We exclude curr)
result = Math.max(result,
2 * countCommon(prev, next)+1);
// check for even length palindrome
// by finding longest common list elements
// beginning from curr and from next
result = Math.max(result,
2*countCommon(curr, next));
// update prev and curr for next iteration
prev = curr;
curr = next;
}
return result;
}
// Utility function to create a new list node
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
/* Driver code*/
public static void main(String[] args)
{
/* Let us create a linked lists to test
the functions
Created list is a: 2->4->3->4->2->15 */
Node head = newNode(2);
head.next = newNode(4);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(2);
head.next.next.next.next.next = newNode(15);
System.out.println(maxPalindrome(head));
}
}
// This code is contributed by
// Prerna Saini.
Python
# Python program to find longest palindrome
# sublist in a list in O(1) time.
# Linked List node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# function for counting the common elements
def countCommon(a, b) :
count = 0
# loop to count common in the list starting
# from node a and b
while ( a != None and b != None ) :
# increment the count for same values
if (a.data == b.data) :
count = count + 1
else:
break
a = a.next
b = b.next
return count
# Returns length of the longest palindrome
# sublist in given list
def maxPalindrome(head) :
result = 0
prev = None
curr = head
# loop till the end of the linked list
while (curr != None) :
# The sublist from head to current
# reversed.
next = curr.next
curr.next = prev
# check for odd length
# palindrome by finding
# longest common list elements
# beginning from prev and
# from next (We exclude curr)
result = max(result,
2 * countCommon(prev, next) + 1)
# check for even length palindrome
# by finding longest common list elements
# beginning from curr and from next
result = max(result,
2 * countCommon(curr, next))
# update prev and curr for next iteration
prev = curr
curr = next
return result
# Utility function to create a new list node
def newNode(key) :
temp = Node(0)
temp.data = key
temp.next = None
return temp
# Driver code
# Let us create a linked lists to test
# the functions
# Created list is a: 2->4->3->4->2->15
head = newNode(2)
head.next = newNode(4)
head.next.next = newNode(3)
head.next.next.next = newNode(4)
head.next.next.next.next = newNode(2)
head.next.next.next.next.next = newNode(15)
print(maxPalindrome(head))
# This code is contributed by Arnab Kundu
C#
// C# program to find longest palindrome
// sublist in a list in O(1) time.
using System;
class GfG
{
//structure of the linked list
public class Node
{
public int data;
public Node next;
}
// function for counting the common elements
static int countCommon(Node a, Node b)
{
int count = 0;
// loop to count common in the list starting
// from node a and b
for (; a != null && b != null;
a = a.next, b = b.next)
// increment the count for same values
if (a.data == b.data)
++count;
else
break;
return count;
}
// Returns length of the longest palindrome
// sublist in given list
static int maxPalindrome(Node head)
{
int result = 0;
Node prev = null, curr = head;
// loop till the end of the linked list
while (curr != null)
{
// The sublist from head to current
// reversed.
Node next = curr.next;
curr.next = prev;
// check for odd length
// palindrome by finding
// longest common list elements
// beginning from prev and
// from next (We exclude curr)
result = Math.Max(result,
2 * countCommon(prev, next)+1);
// check for even length palindrome
// by finding longest common list elements
// beginning from curr and from next
result = Math.Max(result,
2*countCommon(curr, next));
// update prev and curr for next iteration
prev = curr;
curr = next;
}
return result;
}
// Utility function to create a new list node
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
/* Driver code*/
public static void Main(String []args)
{
/* Let us create a linked lists to test
the functions
Created list is a: 2->4->3->4->2->15 */
Node head = newNode(2);
head.next = newNode(4);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(2);
head.next.next.next.next.next = newNode(15);
Console.WriteLine(maxPalindrome(head));
}
}
// This code is contributed by Arnab Kundu
JavaScript
<script>
// Javascript program to find longest palindrome
// sublist in a list in O(1) time.
// structure of the linked list
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
// function for counting the common elements
function countCommon(a, b) {
var count = 0;
// loop to count common in the list starting
// from node a and b
for (; a != null && b != null; a = a.next, b = b.next)
// increment the count for same values
if (a.data == b.data)
++count;
else
break;
return count;
}
// Returns length of the longest palindrome
// sublist in given list
function maxPalindrome(head) {
var result = 0;
var prev = null, curr = head;
// loop till the end of the linked list
while (curr != null) {
// The sublist from head to current
// reversed.
var next = curr.next;
curr.next = prev;
// check for odd length
// palindrome by finding
// longest common list elements
// beginning from prev and
// from next (We exclude curr)
result = Math.max(result, 2 *
countCommon(prev, next) + 1);
// check for even length palindrome
// by finding longest common list elements
// beginning from curr and from next
result = Math.max(result, 2 *
countCommon(curr, next));
// update prev and curr for next iteration
prev = curr;
curr = next;
}
return result;
}
// Utility function to create a new list node
function newNode(key) {
var temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
/* Driver code */
/*
Let us create a linked lists to
test the functions Created list is a:
2->4->3->4->2->15
*/
var head = newNode(2);
head.next = newNode(4);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(2);
head.next.next.next.next.next = newNode(15);
document.write(maxPalindrome(head));
// This code contributed by aashish1995
</script>
Time Complexity : O(n2)
Auxiliary Space: O(1), since no extra space is used.
Note that the above code modifies the given linked list and may not work if modifications to the linked list are not allowed. However, we can finally do one more reverse to get an original list back.
Similar Reads
Javascript Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest
3 min read
Generate an N-length string having longest palindromic substring of length K Given two integers N and K (K ? N), the task is to obtain a string of length N such that maximum length of a palindromic substring of this string is K. Examples: Input: N = 5, K = 3 Output: "abacd" Explanation: Palindromic substrings are "a", "b", "c", "d" and "aba". Therefore, the longest palindrom
4 min read
Sum of all Palindrome Numbers present in a Linked list Given a linked list with integer node values, the task is to find the sum of all Palindrome Numbers present as Node values.Examples: Input: 13 -> 212 -> 22 -> 44 -> 4 -> 3 Output: 285 Explanation: The sum of palindrome numbers {22, 212, 44, 4, 3} is 285Input: 19 -> 22 -> 141 Out
8 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
Length of the longest substring that do not contain any palindrome Given a string of lowercase, find the length of the longest substring that does not contain any palindrome as a substring. Examples: Input : str = "daiict" Output : 3 dai, ict are longest substring that do not contain any palindrome as substring Input : str = "a" Output : 0 a is itself a palindrome
6 min read
Check if a linked list of strings forms a palindrome Given a linked list handling string data, check to see whether data is palindrome or not? For example, Input : a -> bc -> d -> dcb -> a -> NULL Output : True String "abcddcba" is palindrome. Output : a -> bc -> d -> ba -> NULL Output : False String "abcdba" is not palindro
6 min read
Check linked list with a loop is palindrome or not Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop. Examples: Input : 1 -> 2 -> 3 -> 2 /|\ \|/ ------- 1 Output: Palindrome Linked list is 1 2 3 2 1 which is a palindrome. Input : 1 -> 2 -> 3 -> 4 /|\ \|/ ---
14 min read
Length of longest Palindromic Subsequence of even length with no two adjacent characters same Given a string str, the task is to find the length of the longest palindromic subsequence of even length with no two adjacent characters same except the middle characters. Examples: Input: str = "abscrcdba" Output: 6 Explanation: abccba is the required string which has no two consecutive characters
11 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