Given a linked list, find length of the longest palindrome list that exist in that linked list.
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 longest palindromic subarray in 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 given linked list and one by one reverse every prefix of linked list from left. After reversing a prefix, we find the longest common list beginning from reversed prefix and list after the reversed prefix.
Below is the implementation of above idea.
Time Complexity : O(n2)
Note that the above code modifies the given linked list and may not work if modifications to linked list are not allowed. However we can finally do one more reverse to get original list back.
This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- To check a number is palindrome or not without using any extra space
- Check if the characters in a string form a Palindrome in O(1) extra space
- Print reverse of a Linked List without extra space and modifications
- Find pair for given sum in a sorted singly linked without extra space
- Longest palindrome subsequence with O(n) space
- Connect nodes at same level using constant extra space
- Reverse a stack without using extra space in O(n)
- Merge two BSTs with limited extra space
- Merge two sorted arrays with O(1) extra space
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Efficiently merging two sorted arrays with O(1) extra space
- Clone a stack without extra space
- Length of the longest substring that do not contain any palindrome
- Longest palindrome formed by concatenating and reordering strings of equal length
- Find extra node in the second Linked list
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
- Count all palindrome which is square of a palindrome
- Clone a linked list with next and random pointer in O(1) space
- Longest Common Prefix using Linked List