Algo-Sim › Linked Lists
Palindrome Linked List
Easy · Linked Lists · step through it in Java, Python and C++ on your own input
Find the middle with slow/fast, reverse the back half in place, then compare it with the front half: O(1) extra space.
Problem
Return true if the values of the singly linked list starting at head read the same forwards and backwards, and false otherwise.
Constraints
- 1 ≤ number of nodes ≤ 10⁵
- 0 ≤ Node.val ≤ 9
- Follow-up: O(n) time and O(1) extra space
Edge cases to test
- One node
- Even and odd lengths
- Two equal nodes
Follow-up questions
- Should you restore the list?
- Yes if the caller still uses it: reverse the back half again after comparing. Same O(n), O(1).
- What is the simple version?
- Copy values into an array and use two pointers: O(n) space.
Solution
Java
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode prev = null;
while (slow != null) {
ListNode next = slow.next;
slow.next = prev;
prev = slow;
slow = next;
}
ListNode left = head, right = prev;
while (right != null) {
if (left.val != right.val) return false;
left = left.next;
right = right.next;
}
return true;
}Python
def is_palindrome(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
prev = None
while slow:
nxt = slow.next
slow.next = prev
prev, slow = slow, nxt
left, right = head, prev
while right:
if left.val != right.val: return False
left, right = left.next, right.next
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPalindrome(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *prev = nullptr;
while (slow != nullptr) {
ListNode *next = slow->next;
slow->next = prev;
prev = slow;
slow = next;
}
ListNode *left = head, *right = prev;
while (right != nullptr) {
if (left->val != right->val) return false;
left = left->next;
right = right->next;
}
return true;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)