Menu
CoddyTech

Palindrome Linked List

You get a singly linked list stored in two arrays of the same length. Node i holds the value values[i] and links to node next[i], -1 ends the list, and the head is node 0. The nodes are not stored in list order, so follow the links.

Return true if the values read the same from the head to the end as from the end back to the head, and false otherwise.

Function

isPalindrome(next: integer-array, values: integer-array) → boolean
nextinteger-array
the index of the node each node links to, or -1 for the last node
valuesinteger-array
the value held by each node
Returnsboolean
true if the list reads the same in both directions

Constraints

  • 1 ≤ L ≤ 5000, where L is the length of next and of values.
  • -100 ≤ values[i] ≤ 100
  • Each next[i] is -1 or a node index from 0 to L-1.
  • Starting at node 0, the list visits every node exactly once and then reaches -1. There is no cycle.

Examples

Input
next = [4, 3, -1, 2, 1]values = [3, 4, 3, 1, 1]
Output
true
Explanation
The links visit nodes 0, 4, 1, 3, 2, so the list reads 3, 1, 4, 1, 3. The two 3s match, the two 1s match, and the 4 in the middle has no partner to check.
challenge icon

Follow-up

Can you do it in O(L) time with O(1) extra memory?

Reset code
def isPalindrome(next, values):
    # Write code here

Test #1

Test #2

Test #3

Arguments

next = [4, 3, -1, 2, 1]
values = [3, 4, 3, 1, 1]

Expected Output

true