Problem · Tree

Distance Between Two Tree Nodes

MediumAmazonONSITE INTERVIEW
See Amazon hiring insights

Problem statement

You are given a rooted tree whose nodes are numbered from 1 through treeNodes. The arrays treeFrom and treeTo describe the undirected edges of the tree, and root identifies its root.

Given two node IDs source and target, return the number of edges on the unique path between them.

The problem statement continues
Pro

Examples

Example 1

treeNodes = 7treeFrom = [1,1,2,2,3,3]treeTo = [2,3,4,5,6,7]root = 1source = 4target = 7return = 4

The unique path is 4 -> 2 -> 1 -> 3 -> 7, which contains 4 edges.

FastPrep Pro
Reported in 1 Amazon interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 1 more worked example, explained
  • Guided hints and editorial
  • Run your code on real test cases
$9/month

Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week
CodePython 3
Run and Submit unlock with Pro
FastPrep Pro
Reported in 1 Amazon interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 1 more worked example, explained
  • Guided hints and editorial
  • Run your code on real test cases
$9/month

Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week