Lowest Common Ancestor (LCA) Problem | Source Code

WilliamFiset · Intermediate ·⚡ Algorithms & Data Structures ·6y ago

Key Takeaways

This video provides a source code explanation for the Lowest Common Ancestor (LCA) problem in Java, utilizing concepts from a previous video on constructing an Euler tour around a tree and querying the LCA.

Full Transcript

[Music] hello and welcome my name is William today I want to take some time we look at some source code on how to find the lowest common ancestor of two nodes in a tree this video implements the concepts in the previous video where we looked at how to construct an Euler tour around a tree and query the lowest common ancestor if you haven't already watched the explanation video make sure you go and give that a listen and come back all the source code you see today can be found on github at github.com slash will use a slash algorithms alright here we are on the source code for the lowest common ancestor written in Java let's begin by going over an example of how this class is intended to be used in the main method I give three examples of how to do the lowest common ancestor queries the first thing we need to do is actually build a rooted tree in this example I'm reusing the first tree from the slides in the previous video after we've created the tree you can pass the tree into the lowest common ancestor Euler tour constructor at the moment each instance of this class is only meant to handle one tree so if you want to do lowest common ancestor queries on multiple trees you need multiple solvers after the solver is created you can use it to do lowest common ancestor queries in the following example I do three queries to find the LCA of 13 and 14 the LCA of 9 and 11 and the LCA of 12 and 12 let's scroll down to the implementation and take a closer look the first class I want to take a look at is the tree node class you'll notice that this class is mostly the same as before except that it has a new variable n which tracks the number of nodes in the subtree of this tree node including the node itself the tree node also has an index and a list of children most of the methods in this class are accessor methods the only thing when you take a look at are some of the minor changes I made to the build tree method since the routing tree video in the build tree method you'll notice that I'm now counting the number of nodes in the subtree of the current node for our purposes this effectively serves as a nice way to know how many nodes there are in the tree from the root node moving on I want to talk about some of the instance variables in this class the first is and the number of nodes in the tree which is followed by the tour index variable which tracks the index of where we are in the order in tour as we traverse the tree the node depth and the node order arrays are populated during the order in tour they serve to track the depth of each node and a pointer to each node for each index position in the Euler in tour the last map helps keep track of the last occurrence of a node in the ordinary tour and finally is the mint sparse table class to do range minimum queries when creating an instance of the LCA solver you need to provide the root node of the tree you want to do lowest common ancestor queries for from the root node assigned n to be the number of nodes in the tree and call the set up method the setup function is responsible for allocating memory and constructing the order in tour begin by allocating memory for our three arrays node order no depth and last then do a depth first search on the tree to construct the ordering tour after this create a sparse table use the node depth array which was populated during the euler int or the depth-first search method is the one that actually performs the other int or as parameters it tracks the current node and the node depth when the current node becomes null we know that we have reached our base case and can return otherwise visit the current node iterate over all its children recursively the inner visit function call ensures that after visiting a subtree that we revisit the current node this is essential to get the desired or there in tour effect and to traverse the tree as expected the visit function itself is responsible for populating the arrays associated with your layering tour in particular this function will update the nodes array to keep track of pointer to the current node and it will also update the depth array to track the current depth and it will also update the inverse mapping to the or their in tour index so a lot of things going on in the visit function next is the LCA method which finds the lowest common ancestor of two nodes with the indices index 1 and index 2 the first thing we want to do is look inside our last map and find the indices in the order in tour associated with index 1 and index 2 from these values we can extract a left and a right endpoint to make sure the left endpoint always appears before the right endpoint take the min and the max of the indices after we know the left and the right endpoints simply do a range minimum query to find the index of the minimum element in the range l2 our we can do this using the sparse table we created in the setup method and lastly return the tree node object for the lowest common ancestor found in the nodes array below is an implementation of a min sparse table but I'm not going to cover that in this video since I have a dedicated video on sparse tables in my da shorter series if you're interested in that I'll make sure to leave a link below guys thank you for watching I hope you learned something please like this video and subscribe for more mathematics [Music]

Original Description

Source code explanation video of the Lowest Common Ancestor (LCA) problem Lowest Common Ancestor explanation video: https://youtu.be/sD1IoalFomA Sparse Table Video: https://www.youtube.com/watch?v=uUatD9AudXo Source code repository: https://github.com/williamfiset/algorithms#tree-algorithms Video slides: https://github.com/williamfiset/algorithms/tree/master/slides =================================== Practicing for interviews? I have used, and recommend `Cracking the Coding Interview` which got me a job at Google. Link on Amazon: https://amzn.to/3cvMof5 A lot of the content on this channel is inspired by the book `Competitive Programming` by Steven Halim which I frequently use as a resource and reference. Link on Amazon: https://amzn.to/3wC2nix
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from WilliamFiset · WilliamFiset · 0 of 60

← Previous Next →
1 JES Image Manipulation - 2 - Installation
JES Image Manipulation - 2 - Installation
WilliamFiset
2 JES Image Manipulation - 3 - User Interface
JES Image Manipulation - 3 - User Interface
WilliamFiset
3 JES Image Manipulation - 5 - Negative
JES Image Manipulation - 5 - Negative
WilliamFiset
4 JES Image Manipulation - 6 - Black & White
JES Image Manipulation - 6 - Black & White
WilliamFiset
5 JES Image Manipulation - 4 - Grayscale
JES Image Manipulation - 4 - Grayscale
WilliamFiset
6 JES Image Manipulation - 8 - Blur
JES Image Manipulation - 8 - Blur
WilliamFiset
7 JES Image Manipulation - 7 - Edge Detection
JES Image Manipulation - 7 - Edge Detection
WilliamFiset
8 JES Image Manipulation - 9 - Blend
JES Image Manipulation - 9 - Blend
WilliamFiset
9 JES Image Manipulation - 10 - Matte
JES Image Manipulation - 10 - Matte
WilliamFiset
10 JES Image Manipulation - 13 - Rotate90
JES Image Manipulation - 13 - Rotate90
WilliamFiset
11 JES Image Manipulation - 12 - Mirroring Picture
JES Image Manipulation - 12 - Mirroring Picture
WilliamFiset
12 JES Image Manipulation - 11  - Crop Image
JES Image Manipulation - 11 - Crop Image
WilliamFiset
13 JES Image Manipulation - 14 - Stretch picture
JES Image Manipulation - 14 - Stretch picture
WilliamFiset
14 Java Fractal Explorer [6/8]
Java Fractal Explorer [6/8]
WilliamFiset
15 Java Fractal Explorer [4/8]
Java Fractal Explorer [4/8]
WilliamFiset
16 Java Fractal Explorer [8/8]
Java Fractal Explorer [8/8]
WilliamFiset
17 Java Fractal Explorer [5/8]
Java Fractal Explorer [5/8]
WilliamFiset
18 Java Fractal Explorer [2/8]
Java Fractal Explorer [2/8]
WilliamFiset
19 Java Fractal Explorer [7/8]
Java Fractal Explorer [7/8]
WilliamFiset
20 Java Fractal Explorer [1/8]
Java Fractal Explorer [1/8]
WilliamFiset
21 Java Fractal Explorer [3/8]
Java Fractal Explorer [3/8]
WilliamFiset
22 Introduction [Programming Competition Problems]
Introduction [Programming Competition Problems]
WilliamFiset
23 String Manipulation 1 [Programming Competition Problems]
String Manipulation 1 [Programming Competition Problems]
WilliamFiset
24 String Manipulation 2 [Programming Competition Problems]
String Manipulation 2 [Programming Competition Problems]
WilliamFiset
25 Graph Theory 1 [Programming Competition Problems]
Graph Theory 1 [Programming Competition Problems]
WilliamFiset
26 Logic 1 [Programming Competition Problems]
Logic 1 [Programming Competition Problems]
WilliamFiset
27 Grid Problems 1 [Programming Competition Problems]
Grid Problems 1 [Programming Competition Problems]
WilliamFiset
28 Dynamic Programming 1 [Programming Competition Problems]
Dynamic Programming 1 [Programming Competition Problems]
WilliamFiset
29 Introduction to Big-O
Introduction to Big-O
WilliamFiset
30 Dynamic and Static Arrays
Dynamic and Static Arrays
WilliamFiset
31 Dynamic Array Code
Dynamic Array Code
WilliamFiset
32 Linked Lists Introduction
Linked Lists Introduction
WilliamFiset
33 Doubly Linked List Code
Doubly Linked List Code
WilliamFiset
34 Stack Introduction
Stack Introduction
WilliamFiset
35 Stack Implementation
Stack Implementation
WilliamFiset
36 Stack Code
Stack Code
WilliamFiset
37 Queue Introduction
Queue Introduction
WilliamFiset
38 Queue Implementation
Queue Implementation
WilliamFiset
39 Queue Code
Queue Code
WilliamFiset
40 Priority Queue Introduction
Priority Queue Introduction
WilliamFiset
41 Priority Queue Min Heaps and Max Heaps
Priority Queue Min Heaps and Max Heaps
WilliamFiset
42 Priority Queue Inserting Elements
Priority Queue Inserting Elements
WilliamFiset
43 Priority Queue Removing Elements
Priority Queue Removing Elements
WilliamFiset
44 Priority Queue Code
Priority Queue Code
WilliamFiset
45 Union Find Introduction
Union Find Introduction
WilliamFiset
46 Union Find Kruskal's Algorithm
Union Find Kruskal's Algorithm
WilliamFiset
47 Union Find - Union and Find Operations
Union Find - Union and Find Operations
WilliamFiset
48 Union Find Path Compression
Union Find Path Compression
WilliamFiset
49 Union Find Code
Union Find Code
WilliamFiset
50 Binary Search Tree Introduction
Binary Search Tree Introduction
WilliamFiset
51 Binary Search Tree Insertion
Binary Search Tree Insertion
WilliamFiset
52 Binary Search Tree Removal
Binary Search Tree Removal
WilliamFiset
53 Binary Search Tree Traversals
Binary Search Tree Traversals
WilliamFiset
54 Binary Search Tree Code
Binary Search Tree Code
WilliamFiset
55 Fenwick Tree range queries
Fenwick Tree range queries
WilliamFiset
56 Fenwick Tree point updates
Fenwick Tree point updates
WilliamFiset
57 Fenwick Tree construction
Fenwick Tree construction
WilliamFiset
58 Fenwick tree source code
Fenwick tree source code
WilliamFiset
59 Hash table hash function
Hash table hash function
WilliamFiset
60 Hash table separate chaining
Hash table separate chaining
WilliamFiset

This video teaches how to find the Lowest Common Ancestor of two nodes in a tree using Java, covering concepts like Euler tours and sparse tables. It provides a comprehensive explanation of the source code and its implementation.

Key Takeaways
  1. Create a rooted tree
  2. Build an Euler tour around the tree
  3. Construct a sparse table for range minimum queries
  4. Implement the LCA method using the sparse table
  5. Test the LCA method with example queries
💡 The key insight is that the LCA problem can be solved efficiently using an Euler tour and a sparse table, allowing for fast range minimum queries.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →