Start learning free

LESSON 394 OF 635 · LINKED LISTS

Palindrome Linked List in O(n) Time and O(1) Space using JavaScript

Practice O(n) Read the full explanation

You get the head of a singly linked list. Each node holds a digit.

Return true if the values read the same forward and backward. Otherwise, return false.

 

Example 1:

Input: head = [5,1,8,1,5]
Output: true
Explanation: Read backward, it is still 5, 1, 8, 1, 5.
The middle 8 has no partner. That's fine.

Example 2:

Input: head = [2,6,6,9]
Output: false
Explanation: The first value is 2 but the last one is 9.

Example 3:

Input: head = [7]
Output: true
Explanation: A single node reads the same both ways.

 

Constraints:

  • 1 to 100,000 nodes.
  • Each value is a digit from 0 to 9.

 

Follow up: This lesson's solution copies the values. That takes O(n) extra space. A recursive version uses the call stack the same way. As an extra challenge, can you check the list in O(n) time and O(1) extra space?
STEP 1 OF 10
    Ctrl + Enter to check

    JAVASCRIPT · LINKED LISTS

    Palindrome Linked List in JavaScript, explained

    Understanding the Problem

    The core challenge of this problem is to determine if the values in a singly linked list form a palindrome. A palindrome is a sequence that reads the same backward as forward. This problem is significant in various applications such as text processing, data validation, and more.

    Potential pitfalls include handling edge cases like an empty list or a list with a single node, both of which are trivially palindromes.

    Approach

    To solve this problem, we can consider the following approaches:

    Naive Approach

    The naive approach involves copying the values of the linked list into an array and then checking if the array is a palindrome. This approach is simple but requires O(n) space, which is not optimal.

    Optimized Approach

    To achieve O(n) time and O(1) space complexity, we can use the following steps:

    1. Find the middle of the linked list using the slow and fast pointer technique.
    2. Reverse the second half of the linked list.
    3. Compare the first half and the reversed second half of the list.
    4. Restore the original list structure (optional).

    Algorithm

    Let's break down the optimized algorithm step-by-step:

    1. Find the middle of the linked list: Use two pointers, slow and fast. Move slow by one step and fast by two steps. When fast reaches the end, slow will be at the middle.
    2. Reverse the second half: Reverse the nodes starting from the middle to the end of the list.
    3. Compare the two halves: Compare the values of the nodes in the first half and the reversed second half.
    4. Restore the list (optional): Reverse the second half again to restore the original list structure.

    Code Implementation

    /**
     * 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) {
        if (!head || !head.next) return true;
    
        // Step 1: Find the middle of the linked list
        let slow = head, fast = head;
        while (fast && fast.next) {
            slow = slow.next;
            fast = fast.next.next;
        }
    
        // Step 2: Reverse the second half of the list
        let prev = null, curr = slow;
        while (curr) {
            let nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
    
        // Step 3: Compare the first half and the reversed second half
        let firstHalf = head, secondHalf = prev;
        while (secondHalf) {
            if (firstHalf.val !== secondHalf.val) return false;
            firstHalf = firstHalf.next;
            secondHalf = secondHalf.next;
        }
    
        // Optional Step 4: Restore the list (not required for the problem)
        // Reverse the second half again to restore the original list
        // prev = null, curr = slow;
        // while (curr) {
        //     let nextTemp = curr.next;
        //     curr.next = prev;
        //     prev = curr;
        //     curr = nextTemp;
        // }
    
        return true;
    };
    

    Complexity Analysis

    The time complexity of this approach is O(n) because we traverse the list a constant number of times. The space complexity is O(1) because we only use a few pointers and do not allocate extra space proportional to the input size.

    Edge Cases

    Consider the following edge cases:

    • Empty list: Should return true.
    • Single node list: Should return true.
    • List with all identical elements: Should return true.
    • List with different elements: Should return false.

    Testing

    To test the solution comprehensively, consider the following test cases:

    head = [1, 2, 2, 1] // true
    head = [1, 2] // false
    head = [1] // true
    head = [] // true
    head = [1, 2, 3, 2, 1] // true
    head = [1, 2, 3, 4, 5] // false
    

    Use a testing framework like Jest or Mocha to automate the testing process.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller, manageable parts.
    • Think about different approaches and their trade-offs.
    • Practice solving similar problems to improve your problem-solving skills.

    Conclusion

    In this blog post, we discussed how to determine if a singly linked list is a palindrome using an optimized approach with O(n) time and O(1) space complexity. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for improving your algorithmic thinking and coding skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free