Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Binary Tree: Most Recent Common Ancestor

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Binary Tree: Most Recent Common Ancestor. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Clearwater Analytics can represent hierarchical investment data with ordered tree structures. Given a binary search tree and two existing node values, return the value of their most recent, or lowest, common ancestor.

Formal Specification

Implement lowest_common_ancestor(root, p, q).

  • root is a non-empty nested dictionary with the shape { "val": int, "left": node | None, "right": node | None }.
  • p and q are distinct integer values that exist in the tree.
  • Every value in the BST is unique. Values in the left subtree are smaller than the node value, and values in the right subtree are larger.
  • Return the integer value of the lowest node that is an ancestor of both p and q. A node is considered its own ancestor.

Use the BST ordering property rather than traversing every node. Your solution should work for a highly unbalanced tree.

Constraints

  • 1 <= number of nodes <= 10^5
  • Node values are unique integers
  • -10^9 <= node values, p, q <= 10^9
  • Both p and q exist in the tree
  • The tree may be completely skewed

Function Signature

def lowest_common_ancestor(root, p, q):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output