
This blog post explores the problem of checking if a linked list is a palindrome, detailing two approaches: one using additional space with an array and another optimized approach that uses O(1) space. The post includes step-by-step explanations of the algorithms, code snippets, and complexity analysis.
In this blog post, we will explore the problem of determining whether a linked list is a palindrome. This is a common question asked in technical interviews, and understanding how to solve it can significantly enhance your coding skills.
A palindrome is a sequence that reads the same backward as forward. For example, the linked list represented as 1 -> 2 -> 1 -> NULL is a palindrome because it reads the same from both directions. Conversely, a linked list like 1 -> 2 -> 3 -> 4 -> NULL is not a palindrome.
We will discuss two approaches to solve the palindrome check for a linked list:
In this approach, we will copy the linked list elements into an array and then check if the array is a palindrome. Here are the steps:
vector<int> arr;
Node* temp = head;
while (temp != NULL) {
arr.push_back(temp->data);
temp = temp->next;
}
return checkPalindrome(arr);
bool checkPalindrome(vector<int> arr) {
int n = arr.size();
int s = 0, e = n - 1;
while (s <= e) {
if (arr[s] != arr[e]) {
return false;
}
s++;
e--;
}
return true;
}
To achieve O(1) space complexity, we can use the following steps:
Node* getMid(Node* head) {
Node* slow = head;
Node* fast = head->next;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
Node* reverse(Node* head) {
Node* curr = head;
Node* prev = NULL;
while (curr != NULL) {
Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
bool isPalindrome(Node* head) {
if (head == NULL || head->next == NULL) return true;
Node* middle = getMid(head);
Node* secondHalf = reverse(middle->next);
Node* head1 = head;
Node* head2 = secondHalf;
while (head2 != NULL) {
if (head1->data != head2->data) return false;
head1 = head1->next;
head2 = head2->next;
}
middle->next = reverse(secondHalf); // Restore the original list
return true;
}
In this blog post, we discussed how to check if a linked list is a palindrome using two different approaches. The first approach, while straightforward, uses additional space, whereas the second approach is optimized for space efficiency. Understanding both methods equips you with the tools to tackle similar problems in coding interviews and real-world applications.
Feel free to experiment with the code and test it with various linked lists to solidify your understanding. Happy coding!
Paste a YouTube link and let Magica create the key takeaways.
Summarize another video