Ctrl K

Palindromic Subtrees

Hard
You are given a tree of n nodes numbered 0 to n - 1, rooted at node 0. It is described by an array parent: parent[i] is the parent of node i, and parent[0] = -1. Each node carries a letter: node i has labels[i]. To *read* the subtree of node v, write out the readings of the subtrees of all children of v one after another, in increasing order of their numbers, and then append the letter of v itself. Return an array of n booleans whose i-th value is True if the reading of the subtree of node i is a palindrome, and False otherwise. Reading every subtree separately is too slow for large trees, so look for something faster.
Example 1
parent=[-1, 0, 1, 1], labels="zaac" → [False, True, True, True]

Node 1 reads a (node 2), c (node 3), then its own a: aca, a palindrome. The root gives acaz, which is not. Leaves 2 and 3 are single letters.

Example 2
parent=[-1, 0, 0], labels="aba" → [False, True, True]

The root reads b, a, then its own a: baa, not a palindrome.

Example 3
parent=[-1, 2, 0, 2], labels="cqcq" → [False, True, False, True]
Constraints
  • 1 ≤ n ≤ 10⁵
  • len(parent) == len(labels) == n
  • parent[0] == -1, and for i ≥ 1: 0 ≤ parent[i] ≤ n - 1
  • parent describes a valid tree
  • labels consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmallest Shared Territory MediumRegraft Under the Same Letter MediumOne-Swap Word Families HardPurge Twin Folders HardTree Path Without Twin Neighbours Hard
loading Python…
Input
parent=[-1, 0, 1, 1], labels="zaac"
Expected
[False, True, True, True]

Run checks the first 3 tests in your browser. Submit checks all 17 tests on the server, hidden ones included.