234. Palindrome Linked List
| Attempt | Time Required |
|---|---|
| For notes | 32 min 0 sec |
Question
Given the head of a singly linked list, return true if it is a
palindrome
or false otherwise.
Example 1:

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

Input: head = [1,2]
Output: false
Constraints:
- The number of nodes in the list is in the range
[1, 105]. 0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
Approach 1: Brute Force
Intuition
- Using stack data structure as we need to compare the linkedlist with its reverse.
- Stack is Last In First Out.
Algorithm
- Initialize a
stack<int> s&ListNode* curr = head - Loop through the LL using
curr- Push the
curr->valtos curr = curr->next
- Push the
- Assign
curr = head - Loop through the LL using
curr- If
curr->val != s.top()return false - Else
s.pop() curr = curr->next
- If
- Return true
Code
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> s;
ListNode* curr = head;
while (curr) {
s.push(curr->val);
curr = curr->next;
}
curr = head;
while (curr) {
if (curr->val != s.top()) return false;
s.pop();
curr = curr->next;
}
return true;
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity:
(stack space)
Approach 2: Optimal
- Reversing the 2nd half of the LL then comparing
Algorithm
- Find the middle of the linked list using floyds tortoise hare algorithm
- Reverse the second half
curr1for first half,curr2for second half- Loop through the LL till
curr2exists- If
curr1->val != curr2->val- reverse the 2nd half again & return false
- else
curr1 = curr1->next curr2 = curr2->next
- If
- Reverse the LL again
- Return true
Code
class Solution {
public:
ListNode* reverseLL(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* newHead = reverseLL(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
bool isPalindrome(ListNode* head) {
// Edge case for size of LL = 0 or 1
if (head == NULL || head->next == NULL) return true;
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* newHead = reverseLL(slow->next);
ListNode* curr1 = head;
ListNode* curr2 = newHead;
while (curr2) {
if (curr1->val != curr2->val) {
reverseLL(newHead);
return false;
}
curr1 = curr1->next;
curr2 = curr2->next;
}
reverseLL(newHead);
return true;
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity: