-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e1172b0
commit 73b450c
Showing
1 changed file
with
89 additions
and
0 deletions.
There are no files selected for viewing
89 changes: 89 additions & 0 deletions
89
...es/Linear-Data-Structures/Linked-List/Singly-Linked-List/11-check-palindrome.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<int> 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; | ||
} | ||
``` |