Don't overthink: just cache it

I still feel that a lot of times programmers overthink solutions too much. 

They think about a complex algorithm to save few bytes when a simpler one with a little bit of extra memory would do the job just fine. They think about building ML models when a simple rule-based approach would do the job just fine. They think about building solutions that will solve the world's hunger problem - honorable, but honestly it would be better for everyone if they just focused on solving the smaller problem first.

A rule of thumb that works in many more cases than you might imagine is this:



1650. Lowest Common Ancestor of a Binary Tree III
Medium

Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA).

Each node will have a reference to its parent node. The definition for Node is below:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q exist in the tree.
Accepted
284
Submissions
365

You can literally solve it in 5 lines of code: traverse one path up and cache it. Traverse the other, looking for a match in the cache. That's it. 
Why even bother thinking about more complicated solutions than that? As I said many times, memory is cheap - time isn't. Code is below, cheers, ACC.


public Node LowestCommonAncestor(Node p, Node q)
{
    if (p == null || q == null) return null;
    Hashtable path = new Hashtable();
    for (Node temp = p; temp != null; temp = temp.parent) path.Add(temp.val, true);
    for (Node temp = q; temp != null; temp = temp.parent) if (path.ContainsKey(temp.val)) return temp;
    return null;
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval