Palindrome Linked List
Easy
Topics
Given the head of a singly linked list, return true if the sequence of values reads the same forwards and backwards. (The judge passes a plain acyclic list; pos is always -1.)
Example 1
true. What makes this more than a string comparison is that a singly linked list can only be walked forwards; there is no way to step back from the tail.Input: head = [1,2,2,1] Output: true
Example 2
false.Input: head = [1,2] Output: false
Constraints
- 0 <= number of nodes <= 100
- 0 <= Node.val <= 9
Editorial — intuition, approach, complexity and pitfalls
Intuition
A linked list can only be walked forwards, so comparing the first element to the last is not a thing you can do directly. Copying the values into an array makes the list randomly accessible, after which it is the ordinary two-pointer palindrome check. That is O(n) time and O(n) space, and is what the shown solution does.
The O(1)-space answer is the standard follow-up and worth knowing: find the middle with slow/fast pointers, reverse the second half in place, compare the two halves node by node, then reverse it back so the caller's list is unchanged. Same O(n) time, no allocation.
The reason it is more than a trick: reversing the second half turns "walk backwards from the end" into "walk forwards from the middle", which is the only way a singly linked list can be traversed.
Approach
- Walk the list, appending values to a list.
- Compare it to its reverse.
Dry Run
1 -> 2 -> 2 -> 1
values [1,2,2,1]
reversed [1,2,2,1] equal -> true
1 -> 2
values [1,2] vs [2,1] -> falseComplexity
- Time — O(n): one walk plus one comparison.
- Space — O(n): the value array. The reverse-half variant is O(1), which is the version to offer when asked — and it is worth mentioning that it mutates the list mid-flight, so restoring it matters if anything else holds a reference.
Common Pitfalls
- Comparing node objects rather than their values. Distinct nodes holding equal values must compare equal.
- In the O(1) variant, failing to handle an odd length. The middle node belongs to neither half and must be skipped.
- In the O(1) variant, leaving the list reversed. The function is a predicate and should not have side effects.
- Treating the empty list as not a palindrome. Zero and one nodes are both trivially palindromes, and the constraints here allow zero.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head):
vals = []
while head:
vals.append(head.val)
head = head.next
return vals == vals[::-1]import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public boolean isPalindrome(ListNode head) {
java.util.List<Integer> vals = new java.util.ArrayList<>();
while (head != null) {
vals.add(head.val);
head = head.next;
}
int i = 0, j = vals.size() - 1;
while (i < j) {
if (!vals.get(i).equals(vals.get(j))) return false;
i++;
j--;
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: bool isPalindrome(ListNode* head) {
vector<int> vals;
while (head) {
vals.push_back(head->val);
head = head->next;
}
int i = 0, j = (int)vals.size() - 1;
while (i < j) {
if (vals[i] != vals[j]) return false;
i++;
j--;
}
return true;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @return {boolean}
*/ var isPalindrome = function(head) {
const vals = [];
while (head) {
vals.push(head.val);
head = head.next;
}
for (let i = 0, j = vals.length - 1; i < j; i++, j--) if (vals[i] !== vals[j]) return false;
return true;
};