From 73b450c6507f63f4d42f632958ee579ffacd9653 Mon Sep 17 00:00:00 2001 From: Amit Suthar Date: Mon, 18 Dec 2023 12:26:00 +0530 Subject: [PATCH] Palindromic Linked List (#39) --- .../Singly-Linked-List/11-check-palindrome.md | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/Singly-Linked-List/11-check-palindrome.md diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/Singly-Linked-List/11-check-palindrome.md b/Data-Structures/Linear-Data-Structures/Linked-List/Singly-Linked-List/11-check-palindrome.md new file mode 100644 index 0000000..d712b54 --- /dev/null +++ b/Data-Structures/Linear-Data-Structures/Linked-List/Singly-Linked-List/11-check-palindrome.md @@ -0,0 +1,89 @@ +## Check if the LL is palindrome + +Given the head of a singly linked list, return true if it is a +palindrome or false otherwise. + +**Expected TC : O(N), SC : O(1)** + +--- + +### Algorithm + +**1. Brute Force (Stack method)** + +**TC O(2N), SC O(N)** + +```cpp +bool isPalindrome(Node* head) { + stack st; + Node* temp = head; + while (temp != nullptr){ + st.push(temp->val); + temp = temp->next; + } + temp = head; + while (temp != nullptr){ + if (temp->val != st.top()){ + return false; + break; + } + temp = temp->next; + st.pop(); + } + return true; +} +``` + +--- + +**2. Optimal Solution (Reverse half LL)** + +Three Steps to follow : + +1. Find the middle of LL (hare & tortoise method). +2. Reverse one half (obviously the second half). +3. Compare first half with another one. + +**TC O(2N), SC O(1)** + +```cpp +Node* reverse(Node* head){ + // recursion + if (head == nullptr || head->next == nullptr){ + return head; + } + Node* newHead = reverse(head->next); + Node* front = head->next; + front->next = head; + head->next = nullptr; + return newHead; +} + +bool isPalindrome(Node* head) { + if (head == nullptr || head->next != nullptr){ + return true; + } + + // 1. find middle + Node* slow = head; + Node* fast = head; + while (fast->next != nullptr && fast->next->next != nullptr) { // O(N/2) + slow = slow->next; + fast = fast->next->next; + } + + // 2. Reverse + slow->next = reverse(slow->next); + + // compare + slow = slow->next; + ListNode* dummy = head; + + while(slow!=NULL) { + if(dummy->val != slow->val) return false; + dummy = dummy->next; + slow = slow->next; + } + return true; +} +```