Question presented to candidate: "Given the head of a singly linked list, return True if its values read the same forwards and backwards. First tell me the simple way, then do it in O(1) extra space. Please write it in Python."
What a strong answer should cover:
- The simple version: copy values into a Python list and compare (
vals == vals[::-1]), O(n) time and O(n) space. - The O(1)-space version: find the middle with fast and slow pointers, reverse the second half in place, compare value by value, then reverse it back.
- Correct middle for odd and even lengths, and a comparison loop driven by the shorter (second) half.
- Restoring the list before returning, even when the answer is False.
- Python specifics: the tuple-assignment reversal
head.next, prev, head = prev, head, head.next(order matters), comparevalwith==, and the recursive version hits the default recursion limit of 1000 on long lists.
Clarifying questions expected:
- "Is O(n) extra space allowed? May I modify the list temporarily?"
- "Is an empty list a palindrome?"
Code / implementation expected: Yes โ is_palindrome(head) in Python, ideally the O(1)-space version.