Palindrome Linked List — Split, Reverse, Compare

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 210 · Palindrome Linked List

Difficulty: Easy · Pattern: Fast/Slow + Reverse

Approach

  1. Find middle (fast/slow)
  2. Reverse second half in-place
  3. Compare first and second halves
  4. Restore (optional)

Solutions

# Python
def isPalindrome(head):
    # Find middle
    slow = fast = head
    while fast and fast.next:
        slow = slow.next; fast = fast.next.next
    # Reverse second half
    prev, curr = None, slow
    while curr:
        nxt = curr.next; curr.next = prev; prev = curr; curr = nxt
    # Compare
    left, right = head, prev
    while right:
        if left.val != right.val: return False
        left = left.next; right = right.next
    return True
// Java
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, curr = slow;
    while (curr != null) {
        ListNode nxt = curr.next; curr.next = prev; prev = curr; curr = nxt;
    }
    ListNode left = head, right = prev;
    while (right != null) {
        if (left.val != right.val) return false;
        left = left.next; right = right.next;
    }
    return true;
}

Complexity

  • Time: O(n)
  • Space: O(1)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro