234. Palindrome Linked List

Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    let fast = head;
    let slow = head;
    
    // Reach half and end of list
    while(fast && fast.next) {
        fast = fast.next.next;
        slow = slow.next;
    }
    
    // Reverse second half
    let prev = null
    while(slow) {
        let temp = slow.next;
        slow.next = prev;
        prev = slow;
        slow = temp;
    }
    
    let left = head;
    let right = prev; // Last node from previous reverse
    while (right) {
        if (left.val !== right.val) {
            return false;
        }
        left = left.next;
        right = right.next;
    }
    return true;
};

Complexity

  • Time Complexity: O(N)
  • Space Complexity: O(1)

All Solutions