Skip to the solution
EasyDSA11 min read

How do you check if a linked list is a palindrome?

171 views

The problem

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), compare val with ==, 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.

  • linked-list
  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonReverse-the-second-half check, with the list printed afterwards
PythonEvery 0/1 list up to 8 nodes, against the array version

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 34 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What are the tree traversal methods?

Continue