Symmetric Bead Strand

Mediumtwo pointersAlso known as Palindrome Linked List

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

Some customers want a symmetric bracelet: it looks the same whether you start reading from the clasp or from the other end. Before an order is accepted, the app checks the strand, and the device it runs on 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, then check it with two indexes moving in from both ends. Or push every value on a stack and compare while popping.

Both take O(n) time, which is fine, but they also need O(n) extra memory: a full copy of the strand. The task asks for O(1) extra memory, which 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