1607. Longest Mirror Sublist
A jeweller threads beads onto a string, stored as a singly linked list, and wants the longest stretch of consecutive beads that reads the same forwards and backwards. Given head, return the length of the longest run of consecutive nodes whose values form a palindrome. A single node is a run of length 1, and an empty list gives 0. Values fit in a 32-bit integer and the list has at most 2000 nodes. Use O(1) extra space: as you walk the list, reverse the prefix behind you, so the reversed prefix and the untouched suffix can be compared outward from every odd centre (a node) and every even centre (the gap between two nodes). Time O(n^2), extra space O(1).
Example 1
- Input:
- head = [1,2,3,2,1,5]
- Output:
- 5
- Explanation:
The nodes 1, 2, 3, 2, 1 form a palindrome of length 5.
Example 2
- Input:
- head = [4,7,7,9]
- Output:
- 2
- Explanation:
The even-length run 7, 7 is the longest mirror.
Example 3
- Input:
- head = [8,6,5]
- Output:
- 1
- Explanation:
No two neighbours match, so the answer is a single node.
Constraints
0 ≤ length ≤ 2000
values fit in a 32-bit signed integer
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n^2)
- Space
- O(1)