← Amazon Interview Insights

Amazon·Software Engineer·Technical Phone Screen·Intermediate

IntermediatePrefer not to say
Apr 2026

Summary

Amazon coding round, one question on binary trees. Pretty standard stuff but the recursive constraints made it a bit more interesting than I expected.

Questions Asked (1)

Q1

Given the root of a binary tree and two nodes p and q, find their lowest common ancestor. The LCA is the deepest node that has both p and q as descendants, and a node can be a descendant of itself. Solve it recursively with O(N) time and O(H) space.

Algorithms & Data Structures
Author's notes

The recursive framing is what makes this one actually worth thinking about.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the problem and edge cases, then explain the recursive post-order traversal approach where each node returns whether it has found p and/or q. Emphasize that the first node where both are found in different subtrees (or the node itself is one of them) is the LCA, and analyze time and space complexity.

Pro tip: Mention that this solution assumes p and q are guaranteed to exist in the tree; if not, you'd need to verify their presence first. Also, note that the space complexity is O(H) due to recursion stack, which is O(log N) for balanced trees and O(N) for skewed trees.

1. Clarify the problem

Confirm that p and q are distinct and exist in the tree, and that a node can be a descendant of itself. Discuss edge cases like when p or q is the root.

2. Outline recursive strategy

Explain that you'll perform a post-order traversal: recursively search left and right subtrees for p and q. At each node, if the node is p or q, return it; otherwise, combine results from left and right.

3. Define base and recursive cases

Base case: if node is null, return null. If node is p or q, return node. Recursive case: recurse left and right; if both return non-null, current node is LCA; else return the non-null child.

4. Analyze complexity

State that time complexity is O(N) since each node is visited once, and space complexity is O(H) due to recursion stack, where H is tree height.

5. Test with examples

Walk through a simple example (e.g., p and q in different subtrees, or one is ancestor of the other) to validate the logic.

Key Points to Mention

  • Post-order traversal ensures we process children before parent.
  • The LCA is the first node where both p and q are found in different subtrees, or the node itself is one of them.
  • Time complexity O(N) because each node is visited once.
  • Space complexity O(H) due to recursion stack, where H is tree height.
  • Handling of edge cases: p or q is root, p is ancestor of q, etc.
  • Assumption that p and q exist in the tree; if not, additional check needed.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.