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

291 ratings

Stanford University

291 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 3

Huffman codes; introduction to dynamic programming.

- Tim RoughgardenProfessor

Computer Science

So in this video we'll finally discuss Huffman's Algorithm which is a greedy

Â Algorithm that constructs the prefix free binary code minimizing the average

Â encoding length. So, let me just briefly remind you the

Â formal statement of the compositional problem that I left you with last time.

Â So, the input is just a frequency for each symbol I, coming from some alphabet

Â sigma. So the responsibility of the algorithm is

Â to get optimal compression, so to compute an optimal code.

Â So the code has to be binary. We have to use only zeros and ones.

Â We have to be prefix free meaning the encodings of any two characters, neither

Â one can be a prefix of the other, that's to facilitate unambiguous

Â decoding. And finally, the average number of bits

Â needed to encode a character, where the average is with respect to the input

Â frequencies, should be as small as possible.

Â Now remember these kinds of codes correspond to binary trees.

Â The prefix free condition just says that the symbols of sigma should be in one to

Â one correspondence with the leaves of the tree.

Â And finally remember the encoding lengths of the various symbols just correspond to

Â depths of the corresponding leaves. So we can formally express the averaging

Â coding length. Which given a legal tree capital T.

Â I'm using the notation capital L of T. So what do we do?

Â We just take the average over the symbols of the alphabet weighted by the provided

Â frequencies and we just look at the number of bits used to encode that

Â symbol. Equivalently depth of the corresponding

Â leaf in the tree T. So we want the tree that makes this

Â number as small as possible. So this task is a little bit different

Â than any we've seen so far in this course, right?

Â All we're given as an input is an array of numbers and yet we have to produce

Â this actual full blown tree. So how can we just take a bunch of

Â numbers and produce them in a sensible, principled way?

Â Some kind of tree whose leaves correspond to symbols of the alphabet.

Â So let's spend a slide just thinking about, you know, at a high level where

Â would this tree come from, how would you build it up given this unstructured

Â input. So there's certainly no unique answer to

Â this question and one idea which is very natural but that turns out to be sub

Â optimal is to build a tree using a top down approach, which you can also think

Â of as an. Initiation of the divide and conquer

Â algorithm design paradigm. The divide and conquer paradigm, you'll

Â recall, involves breaking the given sub-problem into usually multiple,

Â smaller sub-problems. They're solved recursively, and the

Â solutions are then combined into one for the original problem.

Â Because trees, the desired output here, have a recursive substructure, it's

Â natural to think about applying this paradigm to this problem.

Â Specifically you love to just lean on recursive call to construct for you the

Â left sub tree, another sub call constructing the right

Â sub tree. And then you can fuse the results

Â together under a common root vertex. So it's not clear how to do this

Â partitioning of the symbols into two groups, but one idea to get the most bang

Â for your buck, the most information out of the first bit of your encoding. You

Â might want to split them in, the symbols, into groups that have roughly, as close

Â to as possible, of 50% of the overall frequency.

Â So this topped out approach is sometimes called Fanno-Shannon coding.

Â Fanno was Huffman's graduate adviser. Shannon is the Claude Shannon inventor of

Â information theory. But Huffman in a term paper believe it or

Â not, realized the topped down is not the way to go.

Â The way to go is to build the tree from the bottom up.

Â Not only are we going to get optimal codes, but we're going to get the

Â blazingly fast greedy algorithm that constructs them.

Â So what do I mean by bottom up? I mean we're going to start with just a

Â bunch of nodes, each one labelled with one symbol of the alphabet.

Â So, in effect, we're starting with the leaves of our tree.

Â And then we're going to do successive mergers.

Â We're going to take at each step two sub-trees thus far and link them together

Â as sub-trees under a common internal node.

Â So, I think you'll see what I mean in a picture.

Â So imagine we want to build a tree where the leaves are supposed to be just A, B,

Â C, and D. So one merger would be oh, well let's

Â just take the leaves C and D and link them as siblings under a common ancestor.

Â Now in the second step let's merge the leaf B with the sub-tree we got from the

Â previous merge, the sub-tree comprising the nodes C, D, and their common

Â ancestor. So now of course we have no choice but to

Â merge the only two sub-trees we have left,

Â and then that gives us a single tree. Which is in fact exactly the same

Â lopsided tree we were using in the previous video as a running example.

Â So let me explain what I hope is clear and what is maybe unclear at this

Â juncture. I hope what's intuitively clear is that

Â the bottom of approaches, a systematic way to build trees that have a prescribed

Â set of leaves. So what do we want?

Â We want trees whose leaves are labeled with the symbols of the alphabet sigma.

Â So if we have an alphabet with n symbols, we're going to start with just the N

Â leaves. What does a merger do?

Â Well, there's two things. First of all, it introduces a new

Â internal node, an unlabelled node. And secondly, it takes two of our old

Â subtrees and fuses them into one, merges them into one.

Â We take two subtrees, we make one the left child of this new internal node, the

Â other, the right child of this new internal node.

Â So that drops the number of subtrees we're working with by one.

Â So if we start with the N leaves and we do N minus one successive mergers, what

Â happens? Well on the one hand, we introduce N

Â minus one new unlabeled internal nodes. And on the other hand, we construct a

Â single tree. And the leaves of this tree that we get

Â are in one to one correspondence with the alphabet letters as desired.

Â Now what I don't expect you to have an intuition for is what should we be

Â merging with what and why? Forget about, you know, how do we get an

Â optimal tree at the end of the day. I mean, even just if we wanted to design

Â a greedy algorithm. If we just wanted to make a myopic

Â decision, that looks good right now, how would we even do that?

Â What's our greedy criteria that's going to guide us to merge a particular pair of

Â trees together? So we can re-frame this quandary in the

Â same kind of question we asked for minimum cost spanning trees and really

Â more generally with greedy algorithms. When you're making irrevocable decisions

Â which strikes fear in your heart, is that this decision will come back and haunt

Â you later on. You'll only realize at the end of the

Â algorithm that you made some horrible mistake early on in the algorithm.

Â So just as for MST's, we ask, you know, when can we be sure that including an

Â edge irrevocably is not a mistake, it's safe in the tree that we're building?

Â Here we want to ask, you know, we have to do a merger, we want to do successive

Â mergers and how do we know that a merger is safe?

Â That it doesn't prevent us from eventually computing an optimum solution.

Â Well here's the way to look at things that will at least give us an intuitive

Â conjecture for this question. We'll save the proof for the next video.

Â So what are the ramifications when we merge two subtrees, each containing a

Â collection of symbols? Well, when we merge two subtrees, we

Â introduce a new internal node which unites these two subtrees under them, and

Â if you think about it, at the end of the day on the final tree, this is yet

Â another internal node that's going to be on the root to leaf path,

Â for all of the leaves in these two sub trees.

Â That is, if you're a symbol and you're watching your subtree get merged with

Â somebody else. You're bummed out, your like, man that's

Â another bit in my encoding. That's yet one more node I have to pass

Â through to get back to the root. I think this will become even more clear

Â if we look at an example. So naturally, we'll use our four symbol

Â alphabet A, B, C, D. And initially, before we've merged

Â anything, each of these is just its own leaf A, B.

Â C, D. So there's no internal nodes above 'em.

Â In the sense, everybody's encoding length at the beginning is zero bits.

Â So now, imagine we've merged C and D, we introduce a new internal node, which is

Â the common an-ancestor of these two leaves.

Â And as a result, C and D are bummed out. They said, well, there's one bit that

Â we're going to, to have to incur our encoding length, there's one new internal

Â node we're always going to have to pass through enroute back to the root of the

Â eventual tree. Now suppose next we merge B with the

Â subtree containing both C and D. Well everybody but A is bummed out about,

Â about this merger because we introduce another internal node, and it contributes

Â one bit to the encoding of each of B, C, and D.

Â It contributes an extra one to the encoding of C and D, and it contributes a

Â zero to the encoding of B. So all of their encodings in some sense

Â inc, get incremented, go up by one, compared to how things were before.

Â Now in the final iteration, we have to merge everything together.

Â We have no choice, there's only two sub-trees left.

Â So here, everybody's encoding length gets bumped up by one.

Â So, A finally picks up a bit at zero to encode it and B, C, and D each pick up an

Â additional bit of one, which is prepenned into their encodings thus far.

Â And, in general what you'll notice is that the final encoding length of a

Â symbol, is precisely the number of mergers that its subtree has to endure.

Â Every time your subtree gets merged with somebody else you pick up another bit in

Â your encoding, and that's because there's one more internal node that you're going

Â to have to traverse enroute to the root of the final tree.

Â In this example, the symbols C and D, well they got merged with somebody else

Â in each of the three iterations. So, they're the two symbols that wind up

Â with the encoding length of three. The symbol B, it didn't get merged with

Â anybody in the first iteration, only the second two.

Â That's why it has an encoding length of two.

Â So this is really helpful. So this, lets us relate, the operations

Â that our algorithm actually does, namely mergers back to the objective function

Â that we care about, namely the average encoding length.

Â Mergers increase the encoding lengths of the participating symbols by one.

Â So this allows us to segway into a design of a greedy heuristic for how to do

Â mergers. Let's just think about the very first

Â iteration. So we have our N original symbols, and we

Â have to pick two to merge. And remember the consequences of a merge

Â is going to be an increase in the encoding length by one bit, whichever two

Â symbols we're going to pick. Now we want to do is minimize the average

Â encoding length with respect to the frequencies that were given.

Â So which pair of symbols are we the least unhappy to suffer an increment to their

Â encoding length, was going to be the symbols that are the least frequent.

Â That's going to increase your averaging poding length by the least.

Â So that's the green merging hiuristic. Somethings gotta increase.

Â Pick the ones that are the least frequent to be the ones that get incremented.

Â So that seems like a really good idea of how to proceed in the first iteration.

Â The next question is, how are we going to recurse?

Â So, I'll let you think about that in the following quiz.

Â So let's agree that the first iteration of our greedy heuristic is going to merge

Â together the two symbols that possess the lowest frequencies.

Â Let's call those two symbols little A and little B.

Â The question is then how do we make further progress?

Â What do we do next? Well, one thing that would be really nice

Â is if we could somehow recurse on a smaller subproblem.

Â Well, which smaller subproblem? Well, what does it mean that we've merged

Â together the symbols A and B? Well, If you think about it, in the tree

Â that we finally construct by virtue of us merging A and B, we're forcing the

Â algorithm to output a tree in which A and B are siblings, in which they have

Â exactly the same parent. So what does it mean for the encoding

Â that we compute that A and B are going to be siblings with the same parent?

Â It means that their encodings are going to be identical,

Â save to the lowest order bits. So A will get encoded with a bunch of

Â bits followed by a zero, B will be encoded by exactly the same prefix of

Â bits followed by A1. So they're going to have almost of the

Â same encoding, so for our recursion let's just treat them as the same symbol.

Â So let's introduce a new meta symbol, let's call it AB, which represents the

Â conjunction of A and B. So it's meant to represent all of the

Â frequencies of either one, all of the occurrences of either one of them.

Â But remember the input to the computational problem that we're studying

Â is not just an alphabet, but also frequencies of each of these symbols of

Â that alphabet. So my question for you is when we

Â introduce this new meta symbol A B. What should be the frequency that we

Â define for this meta symbol? All right, so hopefully your intuition

Â suggested answer C, that for this recursion to make sense, for it to

Â conform to our semantics of what this merging does.

Â We should define the frequency of this new meta symbol to be the sum of the

Â frequencies of the two symbols that it's replacing.

Â That's because, remember this meta symbol AB is meant to represent all occurrences

Â of both A and B. So it should be the sum of their

Â frequencies. So I'm now ready to formally describe

Â Huffman's greedy algorithm. Let me first describe it on an example

Â and then I think of the general code will be, self evident.

Â So let's just use our usual example, so we're going to have letters A, B, C, D,

Â with frequencies 60, 25, 10, and 5. So we're going to use the bottom up

Â approach, so we begin with each symbol just as its own node, A, B, C, D.

Â I'm annotating in red the frequencies 60, 25, 10, 5.

Â The greedy heuristic says initially we should merge together the two nodes that

Â have the smallest frequencies. So that would be the C and the D with

Â their frequencies of 10 and 5. Now based on the idea of the last slide

Â when we merged C and D, we replaced them with a meta symbol cd whose frequency is

Â the sum of the frequencies of C and D, namely fifteen.

Â Now we just run another iteration of the greedy algorithm meaning we merge

Â together the two nodes, the two symbols that have the smallest frequencies.

Â So this is now B 25, and CD 15. So now we're down to just two symbols,

Â the original symbol A, which still has frequencies 60 and the in some sense,

Â meta, meta symbol BC, D who is now cumulative frequency is 40.

Â So when we're down to two nodes, that's going to be the point in Huffman's

Â algorithm where we hit the base case and the recursion begins to unwind.

Â So if you just have two symbols to encode there's pretty much only, one sensible

Â way to do it. One is a zero, and one is a one.

Â So at this point, the final recursive call just returns now a tree with two

Â leaves corresponding to the symbols A and BCD.

Â And now is the recursion on lines we in effect undo the mergers.

Â So for each merge we do a corresponding split of the meta node and we replace

Â that with an internal node. And then two children corresponding to

Â the symbols that were merged to make that meta node.

Â So for example, when we want to undo the merge of the B and the CD, we take the

Â node labeled BCD and we split it into two.

Â The left, left child being B, the right child being CD.

Â So the original outer most call, what it gets from its rehersive call is this tree

Â with three nodes and it has to undue it's merger, it merged C and D.

Â So it takes the leaf labeled with symbol CD and splits it into two.

Â It replaces it with a new unlabeled internal node, left child C, right child

Â D. So how does the algorithm work in

Â general? Well just as you'd expect given the discussion on this concrete example.

Â I'm going to take as the base case when the alphabet has just two symbols, in

Â that case the only thing to do is encode one with a zero, the other with a one.

Â Otherwise, we take the two symbols of the alphabet that have the smallest

Â frequencies. You can break ties arbitrarily, it's not

Â going to matter, it's going to be optimal either way.

Â We then replace these two low frequency symbols A and B with meta symbol AB,

Â intended to represent both of them in some sense.

Â As we just discussed with those semantics, we should be defining the

Â frequency of the meta symbol AB as the sum of the frequencies of the symbols

Â that it comprises. We now have a well defined, smaller sub

Â problem. It has one fewer symbol than the one we

Â were given. So, we can recursively compute a solution

Â for it. So, what the recursive call returns is a

Â tree who's leaves are in one to one correspondence with sigma prime.

Â That is, it does not have a leaf labeled A, it does not have a leaf labeled B.

Â It does have a leaf labeled AB, so we want to extend to this tree T prime

Â to be one who's leaves correspond to all of sigma.

Â And the obvious way to do that is to split the leaf labeled AB, replace that

Â with a new internal unlabeled node with two children which are labeled A and B.

Â The resulting tree capital T with leaves and correspondents to the original

Â alphabet sigma is then the final output of Huffman's Algorithm.

Â As always, with a greedy algorithm we may have intuition, it may seem like a good

Â idea. But we can't be sure without a rigorous

Â argument. That is the subject of the next video.

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