FunctionRacerProblemsRace

Complete the Mirror

HardLinked listsPython, JavaScript, TypeScript, Java, C++

Add as few nodes as possible to the end of the list so that it reads the same from front to back as from back to front. Return the head.

For 1 -> 2 -> 2 one more node is enough: 1 -> 2 -> 2 -> 1. A list that already reads the same both ways is returned as it is. The list is passed in as head.

Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.

Example 1

head [1,2,2]
returns [1,2,2,1]

The end 2, 2 mirrors itself already. Only the 1 in front needs a partner.

Example 2

head [1,2,3]
returns [1,2,3,2,1]

Just the last node mirrors itself, so 2 and then 1 are added.

Example 3

head [1,1,2,1]
returns [1,1,2,1,1]

The stretch 1, 2, 1 at the end is fine as it is. The first 1 gets a partner at the end.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems