Palindrome Linked List

25 min · isPalindrome()

A list can mirror itself even though its links only point forward. The trick is deciding how much memory you need to see that mirror.

A palindrome is a sequence that reads the same from left to right and right to left. A singly linked list is a chain of nodes where each node links only to the next one. Given the head of one such list, return true when its values form a palindrome; otherwise, return false.

A few ground rules:

  • Compare node values, not the identities of the nodes that hold them.
  • Both odd-length and even-length lists can be palindromes.
  • A one-node list always returns true.

Constraints

  • 1 <= list length <= 10_000
  • -1_000_000_000 <= Node.val <= 1_000_000_000

Hints

Start with an array

Copy every node value into an array. Arrays let you compare the first value with the last, the second with the second-last, and so on.

Find the halfway point

To avoid the array, move one pointer one node at a time and another two nodes at a time. When the faster pointer finishes, the slower one is at the second half.

Make both halves face you

Reverse the second half in place. Now one pointer can walk from the original head while another walks from the reversed tail, comparing matching values.

Follow-up

Can you restore the second half after the comparison so callers receive the list in its original shape, while keeping O(n) time and O(1) extra space?

Visible cases

Examples

Example 1

ready
Input
head = [
  1,
  2,
  2,
  1
]
Expected
true
Why
the values mirror each other around the center

Example 2

ready
Input
head = [
  1,
  2
]
Expected
false
Why
the first and last values differ

Example 3

ready
Input
head = [
  1
]
Expected
true
Why
a single value reads the same in both directions

Interview signal

Asked at

AmazonMetaMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite