~/problems / Linked lists / Linked lists

Palindrome Linked List

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

ListNode(val, next=None) is in the starter. Keep it.

Write is_palindrome(head) -> bool: True if the values of the singly linked list read the same from the front and from the back, False otherwise.

2 -> 5 -> 8 -> 5 -> 2    True
A list 2, 5, 8, 5, 2 with matching colours pairing the first and last values (2 and 2) and the second and fourth (5 and 5); the middle 8 pairs with itself, so it is a palindrome
3 -> 1 -> 1 -> 3         True  (even length: no middle node)
4 -> 6 -> 4 -> 6         False (4 and 6 at the two ends don't match)
7                        True  (a single node)
  • The list has between 1 and 100,000 nodes; values are digits 0 to 9.
  • You may rearrange the list while you work; only the answer is checked.
  • Copying the values into a Python list passes. For a better answer, use O(1) extra memory.

⭐ Bonus: a speed test with 100,000-node lists earns a star in O(n) time.

Show hint

Find the middle with a slow and a fast pointer, then reverse the second half in place. Now you can walk the first half and the reversed second half side by side.

Topic: Linked lists. Dummy heads, pointer rewiring, fast/slow pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc