Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
| 2 -> 3 -> 4 -> 5 -> 4 -> 3 -> 2 | is a palindrome |
| M -> A -> L -> A-> Y -> A -> L -> A -> M | is a palindrome |
| 2 -> 3 -> 4 -> 5 -> 4 -> 6 -> 2 | is NOT a palindrome |
| K -> A -> M -> A -> L | is NOT a palindrome |
You need to compare the first and last node in the first loop and then compress the list
Time Complexity: O(n2)
bool isPalindrome(Node* head)
{
return isPalindromeRec(&head, head);
}
bool isPalindromeRec(Node **l, Node *r)
{
if (!r) // terminating condition
return true;
// If the sublist is not palindrome then don't need to check further
if (! isPalindromeRec(l, r->link) )
return false;
bool flag = (r->data == (*l)->data);
*l = (*l)->link; // Move l forward
return flag;
}
Method-2: Use reverse method
Step 1. Move to the middle of the list.
Step 2. Reverse the second half
Step 3. compare the first and reversed second half one node at a time,
if they are same return true
else return false.
Step 4. Reverse the 2nd half again to get the original list.
Time Complexity: O(n)
Extra Space used: O(1)
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment