Lowest Common Ancestor III
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Lowest Common Ancestor III
With parent pointers.
Approach 1
Level I: Set of Ancestors
Intuition
Since each node has a
parent pointer, we can trace the path from node p back to the root, storing all ancestors in a Hash Set. Then, trace back from node q. The first ancestor of q that is already in the set is the LCA.Thought Process
- Traverse from
pto root, adding every node toSet. - Traverse from
qto root. - Return first node found in
Set.
⏱ O(H)💾 O(H)
Detailed Dry Run
| Node | Set (Ancestors of P) | In Set? |
|---|---|---|
| P=5 | {5} | - |
| 3 (parent of 5) | {5, 3} | - |
| Q=1 | {5, 3} | NO |
| 3 (parent of 1) | {5, 3} | YES! (Result=3) |
Approach 2
Level II: Depth Alignment
Intuition
We can calculate the depth of both nodes
p and q. Then, move the deeper node up its parent chain until both nodes are at the same depth. From there, move both up together until they meet.Logic
- Calculate
depthPanddepthQ. - Align depths by moving up parent pointers.
- Move both until
p == q.
⏱ O(H)💾 O(1)
Detailed Dry Run
P at depth 3, Q at depth 2. Move P up once. Both at depth 2. Move together -> meet at LCA.
Approach 3
Level III: Optimal (Two Pointers / Intersection)
Intuition
Thought Process
This problem is equivalent to finding the intersection of two linked lists. We use two pointers,
a and b.- Pointer
astarts atp,bstarts atq. - When a pointer reaches the root (
null), it jumps to the other starting node (qorp). - They will eventually meet at the intersection point (the LCA) after at most steps.
Logic
a = (a == null) ? q : a.parent
b = (b == null) ? p : b.parent⏱ O(H)💾 O(1)
Detailed Dry Run
| Step | Ptr A | Ptr B | Notes |
|---|---|---|---|
| 1 | 5 | 1 | Start |
| 2 | 3 | 3 | MEET! (LCA=3) |
⚠️ Common Pitfalls & Tips
Be extremely careful with the
null jumping logic. If you jump at the wrong node, you might enter an infinite loop. The pointers must switch to the other starting node to align their path lengths.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.