Lowest Common Ancestor (LCA) Problem | Source Code
Skills:
Algorithm Basics80%
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
JES Image Manipulation - 2 - Installation
WilliamFiset
JES Image Manipulation - 3 - User Interface
WilliamFiset
JES Image Manipulation - 5 - Negative
WilliamFiset
JES Image Manipulation - 6 - Black & White
WilliamFiset
JES Image Manipulation - 4 - Grayscale
WilliamFiset
JES Image Manipulation - 8 - Blur
WilliamFiset
JES Image Manipulation - 7 - Edge Detection
WilliamFiset
JES Image Manipulation - 9 - Blend
WilliamFiset
JES Image Manipulation - 10 - Matte
WilliamFiset
JES Image Manipulation - 13 - Rotate90
WilliamFiset
JES Image Manipulation - 12 - Mirroring Picture
WilliamFiset
JES Image Manipulation - 11 - Crop Image
WilliamFiset
JES Image Manipulation - 14 - Stretch picture
WilliamFiset
Java Fractal Explorer [6/8]
WilliamFiset
Java Fractal Explorer [4/8]
WilliamFiset
Java Fractal Explorer [8/8]
WilliamFiset
Java Fractal Explorer [5/8]
WilliamFiset
Java Fractal Explorer [2/8]
WilliamFiset
Java Fractal Explorer [7/8]
WilliamFiset
Java Fractal Explorer [1/8]
WilliamFiset
Java Fractal Explorer [3/8]
WilliamFiset
Introduction [Programming Competition Problems]
WilliamFiset
String Manipulation 1 [Programming Competition Problems]
WilliamFiset
String Manipulation 2 [Programming Competition Problems]
WilliamFiset
Graph Theory 1 [Programming Competition Problems]
WilliamFiset
Logic 1 [Programming Competition Problems]
WilliamFiset
Grid Problems 1 [Programming Competition Problems]
WilliamFiset
Dynamic Programming 1 [Programming Competition Problems]
WilliamFiset
Introduction to Big-O
WilliamFiset
Dynamic and Static Arrays
WilliamFiset
Dynamic Array Code
WilliamFiset
Linked Lists Introduction
WilliamFiset
Doubly Linked List Code
WilliamFiset
Stack Introduction
WilliamFiset
Stack Implementation
WilliamFiset
Stack Code
WilliamFiset
Queue Introduction
WilliamFiset
Queue Implementation
WilliamFiset
Queue Code
WilliamFiset
Priority Queue Introduction
WilliamFiset
Priority Queue Min Heaps and Max Heaps
WilliamFiset
Priority Queue Inserting Elements
WilliamFiset
Priority Queue Removing Elements
WilliamFiset
Priority Queue Code
WilliamFiset
Union Find Introduction
WilliamFiset
Union Find Kruskal's Algorithm
WilliamFiset
Union Find - Union and Find Operations
WilliamFiset
Union Find Path Compression
WilliamFiset
Union Find Code
WilliamFiset
Binary Search Tree Introduction
WilliamFiset
Binary Search Tree Insertion
WilliamFiset
Binary Search Tree Removal
WilliamFiset
Binary Search Tree Traversals
WilliamFiset
Binary Search Tree Code
WilliamFiset
Fenwick Tree range queries
WilliamFiset
Fenwick Tree point updates
WilliamFiset
Fenwick Tree construction
WilliamFiset
Fenwick tree source code
WilliamFiset
Hash table hash function
WilliamFiset
Hash table separate chaining
WilliamFiset
More on: Algorithm Basics
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Bloom Filters, Explained Properly
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Medium · Python
🎓
Tutor Explanation
DeepCamp AI