Symmetric Bead Strand

Mediumtwo pointersAlso known as Palindrome Linked List

A jewellery maker designs bracelets in a web app. Each bead is a node holding a color code, linked to the next bead. The app can only walk the strand forwards from the clasp.

Some customers want a symmetric bracelet: the same read from either end. The app checks each order, and its device is short on memory, so it should not copy the strand.

Your task

Write isSymmetric(head). Return true if the sequence of values in the linked list reads the same forwards and backwards, otherwise false.

An empty strand and a single bead both count as symmetric. Aim for O(n) time and O(1) extra memory. You may change the links while you work.

isSymmetric(head: ListNode) → bool

Examples

Example 1
Input
head = [3, 7, 5, 7, 3]
Output
true
Why

Read from either end you get 3, 7, 5, 7, 3. The middle bead, 5, pairs with itself.

Example 2
Input
head = [3, 7, 7, 4]
Output
false
Why

The middle two beads match, but the ends are 3 and 4. Read backwards the strand is 4, 7, 7, 3, which is different.

Constraints

  • 0 ≤ number of beads ≤ 10,000
  • -1,000 ≤ color code ≤ 1,000
Start with brute force

Copy every color code into an array and compare with two indexes moving in from both ends, or push every value on a stack and compare while popping.

Both are O(n) time but also O(n) extra memory for a full copy. O(1) extra memory means working on the links themselves.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code