Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

palindrome LL #39

Merged
merged 1 commit into from
Dec 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
```