Do Two Nodes Share a Proper Ancestor?
Updated
Problem statement
Each row of pairs is [parent,child]. Return whether node IDs a and b share a proper ancestor: a node reached by one or more steps toward parents.
A query node never counts as its own ancestor. If one query is a parent of the other, it can share an earlier ancestor only when it has a parent of its own; a root query has no proper ancestor.
For this exercise, assume a directed acyclic graph that permits several parents; repeated copies of a pair count as one relationship. Only IDs appearing in pairs are represented.
For this exercise, assume equal query IDs are allowed and a query absent from all pairs has no ancestors. Return true exactly when their proper-ancestor sets intersect.
Function
shareProperAncestor(pairs: int[][], a: int, b: int) → booleanExamples
Example 1
pairs = [[1,2]]a = 1b = 2return = falseThis root/child query returns false: query node 1 is not its own ancestor, so no earlier common ancestor exists.
Example 2
pairs = [[1,2],[2,3]]a = 2b = 3return = trueThe answer is true because node 1 is a proper ancestor of both query nodes 2 and 3.
Constraints
- For this exercise, assume
0 <= pairs.length <= 1000. - Each row contains two positive integer IDs, each at most
10^9. - The directed relationships contain no cycles.
- For this exercise, assume query IDs are positive and at most
10^9.
More Karat interview questions
- Parent and Child Counts for Every NodePHONE SCREEN · Seen Sep 2021
- Validate a Latin-Square MatrixPHONE SCREEN · Seen Aug 2020
- Validate a Nonogram GridPHONE SCREEN · Seen Aug 2020
- Nodes With Zero or One ParentPHONE SCREEN · Seen May 2020
- Lowest Common Ancestor in a Rooted TreeONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Task Build Order and File-Change RerunsVanta · PHONE SCREEN
- Resolve Variable Equations with Dependency ErrorsApplied Intuition · PHONE SCREENApplied Intuition interview questions
- Nested Substitutions with Cycle DetectionKikoff · PHONE SCREENKikoff interview questions
- Validate and Resolve Evaluation ChainsPlaid · PHONE SCREEN · ONSITE INTERVIEWPlaid interview questions
- Route Graph Reachability with a Broken LinkFigma · PHONE SCREENFigma interview questions
- Root of the Largest TreeGoldman Sachs · PHONE SCREEN · ONSITE INTERVIEWGoldman Sachs interview questions
- Find the Unique User with Access to Every CameraVerkada · PHONE SCREENVerkada interview questions
- Spreadsheet With Dependent CellsCharacter.AI · PHONE SCREEN
- Unique Transitive Dependent CountsRobinhood · PHONE SCREENRobinhood interview questions
- Evaluate Live Spreadsheet ExpressionsStrala · PHONE SCREEN