easy
linked-list
two-pointers
You are given the values of a singly linked list as an array head, where head[i] is the value of the i-th node. Return true if the linked list reads the same forwards and backwards, and false otherwise.
The classic version of this problem passes a ListNode head; here the node values are supplied as an array so you can focus on the algorithm rather than list plumbing.
The optimal linked-list technique finds the middle with a fast/slow pointer, reverses the second half, and compares the two halves — achieving O(n) time and O(1) extra space. With the array framing you can also compare two pointers moving inward from both ends.
Examples
Example 1
Input: head = [1,2,2,1]
Output: true
Example 2
Input: head = [1,2]
Output: false
Example 3
Input: head = [1]
Output: true
Example 4
Input: head = [1,2,3,2,1]
Output: true
Running will execute all 4 cases.