Problem
Given the head of a singly linked list, determine whether the linked list is a palindrome. Returntrue if the list reads the same forward and backward; otherwise, return false.
For example,
[1, 2, 2, 1] is a palindrome because it reads the same in both directions.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
head = [1, 2, 2, 1]
Output
true
Solution
This solution uses Fast and Slow Pointers and Linked List Reversal to check whether the linked list is a palindrome usingO(1) extra space.
First, we use the Fast and Slow Pointer technique to find the middle of the linked list. The
slow pointer moves one step at a time, while the fast pointer moves two steps at a time.
Once we reach the middle, we reverse the second half of the linked list. This allows us to compare the first half with the second half from opposite directions.
We then use two pointers to compare the values of the first half and the reversed second half. If any pair of values is different, the list is not a palindrome.
If all corresponding values match, the linked list is a palindrome.
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
// Find the middle of the list.
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half.
ListNode secondHalf = reverse(slow);
// Compare both halves.
ListNode firstHalf = head;
ListNode second = secondHalf;
while (second != null) {
if (firstHalf.val != second.val) {
return false;
}
firstHalf = firstHalf.next;
second = second.next;
}
return true;
}
private ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}
Complexity
Finding the middle, reversing the second half, and comparing the two halves each take linear time. Therefore, the overall time complexity isO(n).
The list is reversed in-place using a constant number of pointers, so the extra space complexity is
O(1).
Comments
No comments yet. Ask a question or share what helped.