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 firstname.lastname@example.org. 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.
- Print reverse of a Linked List without extra space and modifications
- To check a number is palindrome or not without using any extra space
- Check linked list with a loop is palindrome or not
- Clone a linked list with next and random pointer in O(1) space
- Check if the characters in a string form a Palindrome in O(1) extra space
- Check if a linked list of strings forms a palindrome
- Check if a doubly linked list of characters is palindrome or not
- Function to check if a singly linked list is palindrome
- Longest Common Prefix using Linked List
- Longest increasing sublist in a linked list
- Run Length Decoding in Linked List
- Check whether the length of given linked list is Even or Odd
- Find length of loop in linked list
- Longest palindrome subsequence with O(n) space
- Find Length of a Linked List (Iterative and Recursive)