Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Trees / DFS High frequency Solution Available Practice Mode

Lowest Common Ancestor of a BST LeetCode Solution

Tags: #Tree #DFS #BST

Approach Summary

If both p and q are smaller than root, LCA is in left subtree. If both larger, right subtree. Otherwise root is the LCA.

Practice Mode 3 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Trees / DFS Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Trees / DFS pattern.

Framework: Trees / DFS • Interview Prep: Tested at FAANG • Explore all Trees / DFS problems & invariants →

How to Recognize This Pattern

  • LCA in BST using BST property

Complexity Analysis

Time Complexity

O(h)

Space Complexity

O(1)

Tags

Tree DFS BST

Frequently Asked Questions

What is the optimal time and space complexity for Lowest Common Ancestor of a BST?
The optimal solution for Lowest Common Ancestor of a BST achieves O(h) runtime complexity and requires O(1) auxiliary space. Time complexity is O(h) where h is tree height (O(log n) for balanced BST, O(n) for skewed). Space complexity is O(1) iterative or O(h) recursive.
How do I identify that Lowest Common Ancestor of a BST requires the Trees / DFS pattern?
In technical interviews, look for key problem signals: LCA in BST using BST property. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Trees / DFS strategy.
What critical edge cases must be handled in Lowest Common Ancestor of a BST?
Essential edge cases to verify include: One of the nodes is the ancestor of the other (e.g. root is p or q; returns that node directly); Nodes are immediate children of root; Nodes reside on opposite sides of root. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Lowest Common Ancestor of a BST?
Lowest Common Ancestor of a BST is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Facebook, LinkedIn.
Buy me a coffee
Daily Practice
0/0