← Questions
Siblings, cousins or neither: two nodes in a tree
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's technical phone screen, last asked Apr 2026. It tests trees and bfs.
Given a rooted tree (each node can have any number of children) and the values of two nodes, say how they are related: "siblings" if they have the same parent, "cousins" if they are at the same depth with different parents, and "others" in every other case, including when either value is not in the tree.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
relationship(root: tuple, a: int, b: int) -> str— a node is(value, [children]); values are unique.
Example
tree = (1, [(2, [(4, []), (5, [])]),
(3, [(6, []), (7, [])])])
relationship(tree, 4, 5) -> "siblings"
relationship(tree, 4, 6) -> "cousins"
relationship(tree, 2, 3) -> "siblings"
relationship(tree, 2, 6) -> "others" # different depths
relationship(tree, 4, 9) -> "others" # 9 is not in the tree
Constraints
- Up to 10^5 nodes; the tree may be deep.
Clarifying questions
- Binary tree or any number of children?
- What if
a == b, or a value is missing? - Is "cousins" only same depth and different parents, or any relative at the same depth?
What a strong answer covers
- One BFS or DFS that records each target's parent and depth, stopping once both are found.
- BFS level by level also works: both found on the same level with different parents means cousins.
- O(n) time, O(width) or O(height) space; iterative to avoid recursion limits.
- Tests: the root as a target, missing targets, a deep chain.
Follow-ups
- Return the lowest common ancestor of the two nodes.
- List every cousin of a given node.
- Answer many queries on the same tree quickly.
Where it's asked
- Amazon · Technical phone screen · Last asked Apr 202660 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
