SDE & MLE Prep

234. Palindrome Linked List

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