Find the Root of a Directed Tree
Updated
Problem statement
You are given every node identifier in a rooted tree and directed edges [parent, child]. Return the unique root identifier.
For this exercise, assume node identifiers are unique nonnegative integers, every non-root node appears as a child exactly once, and the input always describes one valid rooted tree. A single-node tree has no edges.
Function
findTreeRoot(nodes: int[], edges: int[][]) → intExamples
Example 1
nodes = [4,7,9,12]edges = [[7,4],[7,9],[9,12]]return = 7Every node except 7 appears as a child, so 7 is the root.
Example 2
nodes = [42]edges = []return = 42The only node is the root.
Constraints
1 <= nodes.length <= 10^5edges.length = nodes.length - 1- The input describes one valid rooted tree.
More Amazon Onsite Interview questions
- Number of IslandsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Cheapest Flights Within K StopsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course SchedulePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course Schedule IIPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Dungeon GameONSITE INTERVIEW · Seen Nov 2026
- Integer BreakONSITE INTERVIEW · Seen Nov 2026
- LFU CacheONSITE INTERVIEW · Seen Nov 2026
- LRU Cache for Query ResultsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
- First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Top-Down Employee Reporting ForestOkta · ONSITE INTERVIEWOkta interview questions
- Clone a Binary Tree with Random LinksExpedia · ONSITE INTERVIEWExpedia interview questions
- Everyone Under a ManagerAdobe · PHONE SCREENAdobe interview questions
- Find Upstream Tasks of a Failed TaskMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Find Nodes with Invalid Parent LevelsZip · ONSITE INTERVIEWZip interview questions
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Delete Nodes and Return Forest RootsGoogle · ONSITE INTERVIEWGoogle interview questions
- In-Memory Filesystem CommandsPerplexity AI · PHONE SCREEN · ONSITE INTERVIEWPerplexity AI interview questions
- Filter Undesired Comments and Their DescendantsReddit · PHONE SCREEN · ONSITE INTERVIEWReddit interview questions
- JSON Path Lookup with Implicit Array WildcardsMongoDB · ONSITE INTERVIEWMongoDB interview questions