234. Palindrome Linked List
Asked at 15Bloomberg59Amazon57Meta53Google49Microsoft48tcs50IXL93AMD69SAP62Morgan Stanley54eBay53Nvidia39Infosys30Oracle27LinkedIn20
Problem
Decide whether the values of a singly linked list read the same forwards and backwards.
Example: 1→2→2→1 → true; 1→2 → false
Constraints: follow-up: O(n) time and O(1) space.
Find middle, reverse the second half, compare with the first half.
Complexity: O(n) time, O(1) space.
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
prev = None
while slow:
slow.next, prev, slow = prev, slow, slow.next
while prev:
if prev.val != head.val:
return False
prev, head = prev.next, head.next
return True
assert Solution().isPalindrome(make_list([1, 2, 2, 1])) is True
assert Solution().isPalindrome(make_list([1, 2, 3, 2, 1])) is True
assert Solution().isPalindrome(make_list([1, 2])) is False
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
ListNode prev = null;
while (slow != null) { ListNode nxt = slow.next; slow.next = prev; prev = slow; slow = nxt; }
for (; prev != null; prev = prev.next, head = head.next)
if (prev.val != head.val) return false;
return true;
}
}
func isPalindrome(head *ListNode) bool {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
}
var prev *ListNode // reverse the second half, then compare
for slow != nil {
slow.Next, prev, slow = prev, slow, slow.Next
}
for ; prev != nil; prev, head = prev.Next, head.Next {
if prev.Val != head.Val {
return false
}
}
return true
}