Interview Camp: Level: Medium Is Palindrome: Given A Linked List, Determine If It Is A Palindrome
Interview Camp: Level: Medium Is Palindrome: Given A Linked List, Determine If It Is A Palindrome
Interview Camp
Technique: Reverse a Linked List
Level: Medium
Solution:
We need to check if the first and last elements are equal, and then move inwards.
Currently, we cannot do that, because there is no previous pointer.
To do that, we need to reverse the second half of the list. We have already implemented
the reverse function in the lecture solution. If we reverse the second half of the list,
It will look as follows:
K -> A -> Y <- A <- K
Now, we can make 2 pointers at either end of the list and move them inwards to verify.
In order to reverse the second half, we will need to find the middle element of the list.
There are two ways to do this:
1. Count the number of nodes in the list. Then move to the middle node.
2. Make a slow and fast pointer. Advance the fast pointer 2 nodes at a time, and the slow
pointer 1 node at a time. When fast reaches the end of the list, slow should be at the
middle element.
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Both these approaches are fine. We'll implement the second approach here, but you can stick to the
first approach for simplicity.
Pseudocode:
(Note: Never write pseudocode in an actual interview. Unless you're writing a few
lines quickly to plan out your solution. Your actual solution should be in a real
language and use good syntax.)
isPalindrome(Node head):
Node middle = findMedian(head)
last = reverse(middle)
start = start.next;
end = end.next;
}
return true // reached end
// Note: for lists of even size, our median element will be floor(n/2),
// which is ok.
findMedian(head):
fast = head, slow = head
return slow
Test Cases:
Edge Cases: empty list
Base Cases: single element, 2 elements (palindrome/not palindrome)
Regular Cases: even and odd elements (palindrome/not palindrome)
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
start = start.next;
end = end.next;
}
return true;
}
© 2017 Interview Camp (interviewcamp.io)