Palindrome Linked List

Easy · Two Pointers · Linked List · Two Pointers · Stack · Recursion

Problem

Given the head of a singly linked list, return true if its values read the same forwards and backwards, and false otherwise.

Can you do it in O(n) time and O(1) extra space?

Examples

Input: head = [1,2,3,2,1]
Output: true

Read backward, the values are the same 1, 2, 3, 2, 1.

Input: head = [4,5]
Output: false

Read backward, the list is 5, 4.

Input: head = [7,0,0,7]
Output: true

Two pairs of mirrored values and no middle node.

Constraints

Approaches

Follow-up

The fast solution changes the list while it works. If other code may read the list at the same time, that is unsafe even though the list is restored at the end; the O(n)-space copy is then the safer choice. The use cases below reuse the middle-finding and reversing steps for other questions.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…