[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>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to check if sublist from start to end is palindromeboolisPalindrome(Node*start,Node*end){// Store elements of sublist in vectorvector<int>temp;Node*curr=start;while(curr!=end->next){temp.push_back(curr->data);curr=curr->next;}// Two pointer check for palindromeinti=0,j=temp.size()-1;while(i<j){if(temp[i]!=temp[j])returnfalse;i++;j--;}returntrue;}// Function to get length of sublist from start to endintgetLength(Node*start,Node*end){intlen=0;Node*curr=start;// Traverse from start to endwhile(curr!=end->next){len++;curr=curr->next;}returnlen;}// Function to find maximum length palindrome sublistintmaxPalindrome(Node*head){intres=0;// Fix starting pointfor(Node*i=head;i!=nullptr;i=i->next){// Fix ending pointfor(Node*j=i;j!=nullptr;j=j->next){// Check if sublist is palindromeif(isPalindrome(i,j)){intlen=getLength(i,j);// Update maximum lengthres=max(res,len);}}}returnres;}// Driver Codeintmain(){// Creating Linked List: 2->3->7->3->2->12->24Node*head=newNode(2);head->next=newNode(3);head->next->next=newNode(7);head->next->next->next=newNode(3);head->next->next->next->next=newNode(2);head->next->next->next->next->next=newNode(12);head->next->next->next->next->next->next=newNode(24);cout<<maxPalindrome(head);return0;}
[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>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to count common nodes in two listsintcountCommon(Node*a,Node*b){intcount=0;// Compare nodes while both lists are validwhile(a!=nullptr&&b!=nullptr){// If data matches, move both pointersif(a->data==b->data){count++;a=a->next;b=b->next;}elsebreak;}returncount;}// Function to find maximum length palindrome sublistintmaxPalindrome(Node*head){Node*prev=nullptr;Node*curr=head;intres=0;// Traverse the listwhile(curr!=nullptr){Node*next=curr->next;// Reverse current nodecurr->next=prev;// Check for odd length palindrome (center at curr)intoddLen=2*countCommon(prev,next)+1;// Check for even length palindrome (center between prev and curr)intevenLen=2*countCommon(curr,next);// Update maximum lengthres=max(res,max(oddLen,evenLen));// Move pointers forwardprev=curr;curr=next;}returnres;}// Driver Codeintmain(){Node*head=newNode(2);head->next=newNode(3);head->next->next=newNode(7);head->next->next->next=newNode(3);head->next->next->next->next=newNode(2);head->next->next->next->next->next=newNode(12);head->next->next->next->next->next->next=newNode(24);cout<<maxPalindrome(head);return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to count common nodes in two listspublicintcountCommon(Nodea,Nodeb){intcount=0;// Traverse both lists while nodes matchwhile(a!=null&&b!=null){if(a.data==b.data){count++;a=a.next;b=b.next;}elsebreak;}returncount;}// Function to find maximum length palindrome sublistpublicintmaxPalindrome(Nodehead){Nodeprev=null;Nodecurr=head;intres=0;// Traverse list and reverse progressivelywhile(curr!=null){Nodenext=curr.next;// Reverse current nodecurr.next=prev;// Odd length palindrome (center at curr)intoddLen=2*countCommon(prev,next)+1;// Even length palindrome (center between nodes)intevenLen=2*countCommon(curr,next);// Update resultres=Math.max(res,Math.max(oddLen,evenLen));// Move pointersprev=curr;curr=next;}returnres;}// Driver Codepublicstaticvoidmain(String[]args){Nodehead=newNode(2);head.next=newNode(3);head.next.next=newNode(7);head.next.next.next=newNode(3);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(12);head.next.next.next.next.next.next=newNode(24);System.out.println(newGfG().maxPalindrome(head));}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# Function to count common nodes in two listsdefcountCommon(a,b):count=0# Compare nodes while both lists are validwhileaisnotNoneandbisnotNone:# If data matches, move both pointersifa.data==b.data:count+=1a=a.nextb=b.nextelse:breakreturncount# Function to find maximum length palindrome sublistdefmaxPalindrome(head):prev=Nonecurr=headres=0# Traverse the listwhilecurrisnotNone:next=curr.next# Reverse current nodecurr.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 lengthres=max(res,max(oddLen,evenLen))# Move pointers forwardprev=currcurr=nextreturnres# Driver Codeif__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#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGfG{// Function to count common nodes in two listspublicintCountCommon(Nodea,Nodeb){intcount=0;// Traverse both lists while nodes matchwhile(a!=null&&b!=null){if(a.data==b.data){count++;a=a.next;b=b.next;}elsebreak;}returncount;}// Function to find maximum length palindrome sublistpublicintMaxPalindrome(Nodehead){Nodeprev=null;Nodecurr=head;intres=0;// Traverse list and reverse progressivelywhile(curr!=null){Nodenext=curr.next;// Reverse current nodecurr.next=prev;// Odd length palindrome (center at curr)intoddLen=2*CountCommon(prev,next)+1;// Even length palindrome (center between nodes)intevenLen=2*CountCommon(curr,next);// Update resultres=Math.Max(res,Math.Max(oddLen,evenLen));// Move pointersprev=curr;curr=next;}returnres;}// Driver CodepublicstaticvoidMain(string[]args){Nodehead=newNode(2);head.next=newNode(3);head.next.next=newNode(7);head.next.next.next=newNode(3);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(12);head.next.next.next.next.next.next=newNode(24);Console.WriteLine(newGfG().MaxPalindrome(head));}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// Function to count common nodes in two listsfunctioncountCommon(a,b){letcount=0;// Compare nodes while both lists are validwhile(a!==null&&b!==null){// If data matches, move both pointersif(a.data===b.data){count++;a=a.next;b=b.next;}else{break;}}returncount;}// Function to find maximum length palindrome sublistfunctionmaxPalindrome(head){letprev=null;letcurr=head;letres=0;// Traverse the listwhile(curr!==null){letnext=curr.next;// Reverse current nodecurr.next=prev;// Check for odd length palindrome (center at curr)letoddLen=2*countCommon(prev,next)+1;// Check for even length palindrome (center between prev and curr)letevenLen=2*countCommon(curr,next);// Update maximum lengthres=Math.max(res,Math.max(oddLen,evenLen));// Move pointers forwardprev=curr;curr=next;}returnres;}// Driver Codelethead=newNode(2);head.next=newNode(3);head.next.next=newNode(7);head.next.next.next=newNode(3);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(12);head.next.next.next.next.next.next=newNode(24);console.log(maxPalindrome(head));