Ctrl K

Prune Zero-Weight Branches

Medium
You get a tree of n nodes numbered 0 to n - 1, rooted at node 0. The parent of node i is parent[i] (the root has parent[0] = -1), and its weight is weight[i], which may be negative. The weight of a subtree is the sum of the weights of all its nodes. Cut off every subtree whose weight is zero, together with all of its nodes. Return how many nodes remain in the tree.
Example 1
n=6, parent=[-1, 0, 0, 1, 1, 2], weight=[5, 3, 2, -1, -2, 1] → 3

The subtree of node 1 weighs 3 - 1 - 2 = 0, so it goes together with nodes 3 and 4. Nodes 0, 2 and 5 remain (their subtrees weigh 8 and 3).

Example 2
n=4, parent=[-1, 0, 1, 1], weight=[2, -4, 1, 1] → 0

The whole tree sums to 2 - 4 + 1 + 1 = 0, so all of it is removed.

Example 3
n=3, parent=[-1, 0, 0], weight=[0, 4, 7] → 3

Node 0 itself weighs zero, but what counts is its subtree sum, 11. Nothing is removed.

Constraints
  • 1 ≤ n ≤ 10⁵
  • len(parent) == len(weight) == n
  • parent[0] == -1, otherwise 0 ≤ parent[i] < n
  • -10⁵ ≤ weight[i] ≤ 10⁵
  • parent describes a valid tree rooted at 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStop a Process Branch MediumSmallest Shared Territory MediumRooms Open from the Hall MediumTreasure Gates Race MediumMeeting Point on a Route Hard
loading Python…
Input
n=6, parent=[-1, 0, 0, 1, 1, 2], weight=[5, 3, 2, -1, -2, 1]
Expected
3

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