Skip to content

Practice Find Subtree Sizes After Changes

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#3331
LeetCode Problem

Find Subtree Sizes After Changes

Problem Statement

The array parent describes a tree rooted at 0, with parent[0] = -1, and s gives each node’s character. Using the original tree, find each non-root node’s nearest strict ancestor with the same character. Simultaneously change that node’s parent to the matching ancestor, if one exists; otherwise keep its original parent. Return every node’s subtree size in the resulting tree, including the node itself.

Source: Find Subtree Sizes After Changes on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
parent = [-1,0,0,1,1,1], s = "abaabc"
Output
[6,3,1,1,1,1]

# Example 2

Input
parent = [-1,0,4,0,1], s = "abbba"
Output
[5,2,1,1,1]

Constraints

n == parent.length == s.length
1 <= n <= 10^5
0 <= parent[i] <= n - 1 for all i >= 1.
parent[0] == -1
parent represents a valid tree.
s consists only of lowercase English letters.

Related LeetCode Problems

Practice more problems similar to Find Subtree Sizes After Changes.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.