Count Distinct Rooted-Tree Grafts
Updated
Problem statement
You are given two rooted trees. Tree 1 is encoded by parent1 and Tree 2 by parent2. In each array, node 0 is the root and has parent -1; for every other node i, parent[i] is its parent.
Perform exactly one operation:
- Choose any node
uin Tree 2 and keep the complete subtree rooted atu. - Choose any leaf in Tree 1 and attach
uas a new child of that leaf. - Discard every node of Tree 2 outside the chosen subtree.
Two results are identical when one can be transformed into the other by reordering children and renumbering non-root nodes. Return the number of distinct rooted, unordered tree structures obtainable over all valid choices.
Function
countDistinctGrafts(parent1: int[], parent2: int[]) → intExamples
Example 1
parent1 = [-1]parent2 = [-1,0]return = 2Keeping the root of Tree 2 creates a three-node chain; keeping only its leaf creates a two-node chain.
Example 2
parent1 = [-1,0,0]parent2 = [-1]return = 1The two leaves of Tree 1 are structurally symmetric, so both attachment choices produce the same rooted tree.
Example 3
parent1 = [-1,0]parent2 = [-1,0,0]return = 2Choosing the branching root or choosing either symmetric leaf yields two distinct structures.
Constraints
1 <= parent1.length, parent2.length <= 60parent1[0] = parent2[0] = -1- For each
i > 0,0 <= parent[i] < i. - Both arrays describe valid rooted trees.
Source note: The source image is a source-neutral excerpt of the author-reported prompt.
More The D.E. Shaw Group interview questions
- IPOPHONE SCREEN · Seen Nov 2026
- Print Numbers in Turn with Three ThreadsPHONE SCREEN · Seen Nov 2026
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Koko Eating BananasPHONE SCREEN · Seen Nov 2026
- Sum of Smallest Non-DivisorsPHONE SCREEN · Seen Nov 2026
- Remove the Fewest Magic BeansPHONE SCREEN · Seen Oct 2026
- Equal-Weight Portfolio VariancePHONE SCREEN · Seen Oct 2026
- Decode WaysPHONE SCREEN · Seen Sep 2026
- Maximum L1 Distance Between Equal-Length SubarraysPHONE SCREEN · Seen Jul 2026
- Count Lucky TicketsOA · Seen Nov 2026
Similar questions at other companies
- Account Roles With Parent-User InheritanceStripe · PHONE SCREENStripe interview questions
- Filesystem Hash TreeCursor · PHONE SCREEN · ONSITE INTERVIEWCursor interview questions
- JSON Path Lookup with Implicit Array WildcardsMongoDB · ONSITE INTERVIEWMongoDB interview questions
- Recover a Tree From Preorder TraversalGrammarly · PHONE SCREEN
- Lowest Common Manager for Employee GroupsAmazon · PHONE SCREEN
- Spreadsheet With Dependent CellsCharacter.AI · PHONE SCREEN
- Lowest Common Manager for Employee GroupsGoogle · PHONE SCREENGoogle interview questions
- Evaluate Live Spreadsheet ExpressionsStrala · PHONE SCREEN
- ClayWorkspace Resource TreeGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- Serialize and Deserialize a Binary TreeNVIDIA · PHONE SCREENNVIDIA interview questions