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