The primary topics in this part of the specialization are: greedy algorithms (scheduling, minimum spanning trees, clustering, Huffman codes) and dynamic programming (knapsack, sequence alignment, optimal search trees).

Loading...

From the course by Stanford University

Greedy Algorithms, Minimum Spanning Trees, and Dynamic Programming

272 ratings

Stanford University

272 ratings

Course 3 of 4 in the Specialization Algorithms

The primary topics in this part of the specialization are: greedy algorithms (scheduling, minimum spanning trees, clustering, Huffman codes) and dynamic programming (knapsack, sequence alignment, optimal search trees).

From the lesson

Week 2

Kruskal's MST algorithm and applications to clustering; advanced union-find (optional).

- Tim RoughgardenProfessor

Computer Science

So let me now introduce you to the union-find data structure.

Â Let's not lose sight of our goal.

Â Our goal is to be able check for cycles in Kruskal's algorithm in constant time.

Â So the first and most basic idea behind this union-find data structure

Â implementation, is we're going to maintain a linked structure for each group, that is

Â for each connected component with respect to the edges Kruskal has chosen thus far.

Â By link structure I just mean each vertex of the graph

Â is going to have an extra pointer field.

Â In addition, with each group,

Â with each connected component, we're going to designate one vertex.

Â And we don't care which one.

Â Just some vertex from this connected component as the leader

Â vertex of that component.

Â All right, so what is the point of these extra pointers at each vertex and

Â what is the point of having these leaders?

Â Well a key invariant that we're going to maintain is that a given vertex,

Â with its extra pointer, points to the leader vertex of its connected component.

Â So for example maybe we have two different connected components with

Â three vertices each, one containing the vertices u, v, and

Â w, another containing the vertices x, y and z.

Â Any of these three vertices could be the leader of each of these two components, so

Â perhaps u happens to be the leader vertex of the first component and

Â x happens to be the leader vertex of the second component, and then the invariant

Â just says every vertex should be pointing to the leader of its component.

Â So v and w should be pointing to u,

Â u has its own pointer, it should be pointing to itself.

Â Similarly in the second component x is pointing to itself, y points to x and

Â z also points to x.

Â So in blue here are the actual edges of the graph and

Â in green there are these sort of extra edge pointers that we've invented where

Â everybody's pointing back to the leader of their component.

Â And so one very simple thing in this setup, which turns out to be a good idea,

Â is each component is in effect inheriting the name of its leader vertex.

Â So we refer to a group, we refer to a component via the object, via the vertex,

Â who happens to be the representative, who happens to be the leader.

Â And what's kind of amazing is even just this very simple scaffolding on

Â the connected components is enough to have constant time cycle checks provided

Â the invariant is satisfied.

Â Well, how do we do that.

Â So remember that checking if adding the edge uv is going to create a cycle

Â boils down to checking whether there's already a path between u and v.

Â Well, there's already a path between u and v if and

Â only if they're in the same connected component.

Â Given two vertices, u and v.

Â How do we know if they're in the same connected component?

Â We just follow the respective leader pointers and

Â we see if we get to the same place.

Â If they're in the same component, we get the same leader.

Â If they're in different components, we get different leaders.

Â So, checking for a cycle just involves for each of u and

Â v, comparing a quality of leader pointers that is clearly constant time.

Â More generally the way you implement the find operation for

Â this flavor of disjoint union data structure is you simply return

Â the leader pointer of the object that you were handed.

Â So if you're given a vertex, you just follow the leader pointer of that vertex,

Â and you return wherever you wind up.

Â So that's pretty excellent as long as in this simple data structure the invariants

Â satisfied we have are desired implementation of constant time

Â cycle checks.

Â But and certainly this is a recurring theme in our data structure discussions.

Â Whenever you have a data structure and it needs to maintain an invariant.

Â Whenever you do an operation that changes the data structure.

Â So in this case when you do a union fusing two groups together.

Â You have to worry,

Â well does the invariant get destroyed when you do that operation and

Â if it does how are you going to restore the invariant without doing undue work.

Â So in the present context of Kruskal's algorithm here's how this plays out.

Â So we're happily doing our constant time cycle checks whenever an edge creates

Â a cycle we don't do anything, we skip the edge, we don't change our data structure,

Â we move on.

Â The issue is when we have a new edge and

Â it doesn't create a cycle, our cycle check fails.

Â Now Kruskal's algorithm dictates that we add this edge into the set capital T that

Â we're building and that fuses two connected components together.

Â But remember we have this invariant,

Â every vertex should point to the leader of it's component.

Â Well if we had component A and we had component B,

Â they are both pointing to the leader vertex of their respective components.

Â Now when these components fuse into one,

Â we've gotta do some updating of leader pointers.

Â In particular, there used to be two leaders, now there has to be just one.

Â And we have to rewire the leader pointers to restore the invariant.

Â So to make sure you're clear on this important problem.

Â Let me ask you the following question.

Â So consider the case when at some point in Kruskal's algorithm,

Â a new edge is added and two connected components fuse into one,

Â now to restore the invariant you have to some leader pointer updates.

Â In the worst case, asymptotically, how many leader pointer updates might be

Â required in order to restore the invariance?

Â So, the answer to this question, somewhat alarmingly, is the third answer.

Â So, it might require a linear number in the number vertices n

Â pointer updates to restore the invariant.

Â Maybe one easy way to see that is just imagine the very last edge that Kruskal's

Â going to add in the set T,

Â the one which fuses the final two connected components down into one.

Â For all you know, those two components have exactly the same size.

Â They have n over 2 vertices each.

Â You're going down from two leader pointers to one.

Â One of those sets of n over 2 vertices are going to have to

Â inherit the leader pointers from the other side.

Â So one of the two sets is going to have to have n over 2 vertices get their leader

Â pointer updated.

Â So that's a bummer.

Â We were sort of hoping for a near linear time bound, but if every,

Â each one of our linear number of edge additions might trigger a linear number

Â of leader pointer updates that seems to be giving rise to a quadratic time bound.

Â But remember when I introduced the union-find data structure I only said that

Â first idea was idea number one.

Â Presumably there's an idea number two and here it is.

Â And it's very natural, if you were coding up an implementation of union-find

Â data structure you would probably very naturally do this optimization yourself.

Â All right, so

Â consider the moment in time in which some component A merges with some component B.

Â Each of these two components currently has their own respective leader vertex, and

Â all vertices from that group are pointing to that leader vertex.

Â Now when they fuse, what are you going to do?

Â The first obvious thing to do is say,

Â well let's not bother computing some totally new leader.

Â Let's either re-use the leader from group A or the leader from group B.

Â That way it, for example, we retain the leader from group A, the only leader

Â pointers that need to be rewired are the ones that come from component B.

Â The vertices in component A can keep their same leader vertex and

Â their same leader pointers as before.

Â So that's the first point.

Â Let's just have a new union of two components inherit the leader of one

Â of the constituent parts.

Â Now, if you're going to retain one of the two leaders,

Â which one are you going to retain?

Â Maybe one the components is 1,000 vertices.

Â The other component only has 100 vertices.

Â Well given the choice you're certainly going to keep the leader from the bigger,

Â from the first component.

Â That way you only have to rewire the 100 leader pointers of the second group.

Â Right if you kept the leader of the second group you'd have to rewire the 1,000

Â pointers from the first group and that seems silly and wasteful.

Â So the obvious way to implement a merge is you just keep the leader of the bigger

Â group, and rewire everybody from the second group, the smaller group.

Â So you should notice that in order to actually implement this optimization

Â where you always retain the leader of the larger group,

Â you have to be able to quickly determine which of the two groups is larger, but

Â you can augment the data structure we've discussed to facilitate that.

Â So just with each group, you just keep a count of how many vertices are in that

Â group so you maintain a size field for each group.

Â That allows you to check in constant time what's the population of two

Â different groups and figure out, again in constant time, which one's bigger.

Â And notice that when you fuse two groups together it's easier to maintain the size

Â field, it's just the sum of the sizes of the two constituent parts.

Â So let me know revisit the question from the previous slide.

Â In the worst case given this optimization, how many leader pointers, asymptotically,

Â might you have to rewire when you merge two components together?

Â Well unfortunately, this song remains the same.

Â The answer is still the third one, and it's because for

Â exactly the same reason as on the previous slide.

Â It still might be the case that say in the final iteration of Kruskal

Â you're merging two components that both have size n over 2, so it doesn't matter.

Â I mean no matter which leader you choose you're going to be stuck

Â updating the leader pointers of n over 2 or theta of n vertices.

Â So while this is clearly a smart practical optimization, it doesn't seem to be buying

Â us anything in our asymptotic analysis of the running time.

Â However, however, what if we think about the work done in all of

Â these leader pointers updates in the following different way.

Â Rather than asking how many updates might a merging of two components trigger,

Â let's adopt a vertex-centric view.

Â Let's suppose you're one of the vertices of this graph, so initially the beginning

Â of Kruskal's algorithm you're in your own isolated connected component,

Â you just point to yourself.

Â You're your own leader.

Â And then as Kruskal's algorithm runs it's course,

Â your leader pointer will periodically get updated.

Â At some point you're no longer pointing to yourself.

Â You're pointing to some other vertex.

Â Then at some point you're pointer gets updated again, you're pointing to yet

Â some other vertex and so on.

Â How many times over the entire trajectory of Kruskal's algorithm,

Â in light of our new optimization,

Â might you as some vertex of this graph have your leader pointer updated?

Â Well here's the very cool answer.

Â The answer is the second one.

Â So while it remains true that if you always have

Â the union of two groups inherit the leader pointer of the larger one,

Â it's still true that a given fusion might trigger a linear number of leader

Â pointer updates, each vertex will only see its leader pointer

Â updated a logarithmic number of times over the course of Kruskal's algorithm.

Â What is the reason for this?

Â Well, suppose you're a vertex and you're in some group and

Â it has maybe 20 vertices, so you're 1 of 20.

Â Now, suppose at some point your leader pointer gets updated.

Â Why did that happen?

Â Well, it meant that your group of 20 vertices merged

Â with some other group that has to be bigger.

Â Remember, your leader pointer only gets rewired in a fusion if you were in

Â the smaller group.

Â So you're joining a group at least as big as yours.

Â So the size of the union, the size of your new community,

Â your new connected component is at least double the size of your previous one.

Â So the bottom line is every time you as a vertex has your leader pointer updated,

Â the population in the component to which you belong

Â is at least twice as large as before.

Â Now, you started the connecting component of size one.

Â The connecting component is not going to have more than n vertices.

Â So the number of doublings you might have to endure ss at most log base 2 of n.

Â So that bounds how many leader pointers you will see as a vertex in this graph.

Â So in light of that very cool operation we can now give a good running time analysis

Â of Kruskal's algorithm using the union-find data structure,

Â using the scaffolding on the connected component structure to do cycle checks.

Â We of course have not changed the preprocessing step.

Â We're still sorting the edges from cheapest to most expensive at

Â the beginning of the algorithm, and that still takes O(m log n) time.

Â So what work do we have to do, beyond this sorting preprocessing step?

Â Well fundamentally, Kruskal's algorithm is just about these cycle checks.

Â In each iteration of the for loop, we have to check if adding

Â a given edge would create a cycle with those edges we've already added.

Â And, the whole point of the union-find scaffolding, these link structures,

Â is that we can check cycles in constant time.

Â Just given a edge, we look at the leader pointers of its endpoints, and

Â a cycle will be created if and only if their leader pointers are identical.

Â So for the cycle checking,

Â we only do constant time for each of the O of m iterations.

Â But the final source of work is maintaining this union-find

Â data structure,

Â restoring the invariant each time we add a new edge to the set capital T.

Â And here the good idea is we're not going to just bound the worst case

Â running time of these leader pointers for each iteration, because that could be

Â too expensive that could be up to linear in just a single iteration.

Â Rather we're going to do a global analysis,

Â thinking about the total number reader pointers that ever occur,

Â on the previous slide we observed that for a single vertex,

Â it's only going to endure a logarithmic number of leader pointer updates.

Â So something over all of the n vertices, the total work done for

Â leader pointer updates is only n log n.

Â So even though we might do a linear amount of pointer updates in just

Â one iteration of this for loop, we still have this global upper bound of n log n on

Â the total number of leader pointer updates.

Â Very cool.

Â So looking over this tally, we observe the stunning fact that the bottleneck for

Â this implementation of Kruskal's algorithm is actually sorting.

Â So we do more work in the preprocessing step,

Â n log n, than we do in the entire for loop, which is only m plus n log n.

Â So that gives us an overall running time down of O(m log n)

Â matching the theoretical performance that we achieved

Â in Prim's algorithm implemented with heaps.

Â So just like with our heap-based implementation of Prim's algorithm,

Â we get a running time which is almost linear.

Â Only a logarithmic factor's slower than reading the input.

Â And just like with Prim's algorithm,

Â you should find Kruskal's algorithm to be very competitive in practice.

Â Coursera provides universal access to the worldâ€™s best education, partnering with top universities and organizations to offer courses online.