Lowest Common Ancestor in a Rooted Tree
Updated
Problem statement
Each row of pairs is [parent,child]. Return the lowest common ancestor of node IDs a and b.
For this exercise, assume the unique relationships form one rooted tree when nonempty: they are connected, acyclic, and each non-root node has exactly one parent. Repeated copies of an edge have no effect. Only IDs appearing in a pair are represented; empty input represents an empty tree.
For this exercise, assume a node counts as its own ancestor for this LCA query. Return the deepest shared node in the rooted tree. If either query ID is not represented, return -1; this includes empty input.
Function
lowestCommonAncestor(pairs: int[][], a: int, b: int) → intExamples
Example 1
pairs = [[8,2],[8,9],[2,5],[2,6]]a = 5b = 6return = 2This tree gives deepest shared node 2 for siblings 5 and 6.
Example 2
pairs = [[1,2],[2,3]]a = 2b = 3return = 2This ancestor query returns node 2 itself, because a node counts as its own ancestor.
Constraints
- For this exercise, assume
0 <= pairs.length <= 1000. - Each row contains two positive integer IDs, each at most
10^9. - After duplicate edges are ignored, nonempty input represents one rooted tree.
- For this exercise, assume query IDs are positive integers at most
10^9.
More Intuit interview questions
- VIP and Regular Service SchedulerPHONE SCREEN · Seen Nov 2026
- Longest Uninterrupted Work BlockPHONE SCREEN · Seen Sep 2026
- VIP-Priority Fixed-Window Rate LimiterPHONE SCREEN · Seen Aug 2026
- Small Business Network: Degrees of SeparationPHONE SCREEN · Seen May 2026
- Longest Common SubstringPHONE SCREEN · Seen May 2021
- Zero or One Parent Groups in a TreePHONE SCREEN · Seen Feb 2020
- Number of IslandsONSITE INTERVIEW · Seen Nov 2026
- Employee Promotion OpportunitiesOA · Seen Oct 2026
- Next Pascal Row CoefficientOA · Seen Oct 2026
- Parse Router LogsOA · Seen Oct 2026
Similar questions at other companies
- In-Memory Filesystem CommandsPerplexity AI · PHONE SCREEN · ONSITE INTERVIEWPerplexity AI interview questions
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Lowest Common Ancestor in an N-ary TreeGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Lowest Common Ancestor in an N-ary TreeAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Tree Selection and VisibilityJane Street · PHONE SCREENJane Street interview questions
- Account Roles With Parent-User InheritanceStripe · PHONE SCREENStripe interview questions
- Worst-Performing Ads by CTR in a Campaign TreeUber · PHONE SCREENUber interview questions
- Validate a BST with a Custom ComparisonApple · PHONE SCREENApple interview questions
- Build a File Tree from Streamed RecordsNextdoor · PHONE SCREENNextdoor interview questions
- Construct a Binary Tree from Preorder and InordereBay · PHONE SCREENeBay interview questions