Palindrome Linked List

Check linked-list palindromicity by reversing the second half in place and walking both halves.

Easy
Time O(n) Space O(1)
LeetCode
4 min read
fast-slow linked-list

Problem#

Return true if the singly linked list reads the same forward and backward.

Examples#

  • [1,2,2,1]true
  • [1,2]false

Constraints#

  • Length in [1, 10^5].

Approach#

  1. Find the middle with fast/slow.
  2. Reverse the second half in place.
  3. Walk first half and reversed second half; if they match throughout, palindrome.

Solution#

Palindrome Linked List
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
// Reverse from slow to end.
ListNode* prev = nullptr;
while (slow) {
ListNode* nxt = slow->next;
slow->next = prev;
prev = slow;
slow = nxt;
}
// Compare halves.
ListNode *a = head, *b = prev;
while (b) {
if (a->val != b->val) return false;
a = a->next; b = b->next;
}
return true;
}
};

Editorial#

The middle-then-reverse approach gives O(1) space. Comparing until the shorter (reversed second) half is exhausted handles odd lengths automatically: the middle element pairs with itself trivially. Optionally restore the list by reversing the second half again before returning.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.