Brought to you by Interview Accelerator at

For weekly coding practice, check out

*Largest Rectangle Under A Histogram*

Today’s problem is about finding the largest rectangle within a histogram. We’ll explore a linear time solution.

I encourage you to try and solve this problem before looking at the video. Then post your solution below.

I give you two options toward the end of the video, so let me know which problem you’d like covered next.

If you want to learn data structures and algorithms, visit and sign up to learn about my upcoming course.

hey guys I'm covering a very popular problem this week and it's about finding the largest rectangle inside of a histogram so it may seem complicated at first but I go through my entire thought process and you'll see at the end how simple the solution is so also let me know in the comment section below what you think of the solution and if you have your own solutions so let's dive right into it so we are given a histogram that looks something like this and we have to find the maximum rectangular area within it okay so let's look at this example we have an array that you translated into a histogram over here right so just a few questions on it all of these numbers over here they correspond to the heights of these bars yeah and what about the width so that constant right unit one okay so let's say the widths are just one unit for all of these so let's see how I would do it the first thing that comes to mind is that I would iterate through this entire array for each index out see that what are what are its neighbors so let me just give you an example let's say I am at 3 right I'm at reading the array and I I'm done with Prior indices I'm at 3 right now and then for this index I'll say okay what are the values to my right and I will go all the way till the next value is less than me right so let's say over here I stop right there right and I'll do the same thing what are the values to my left and I'll go all the way till some value the next value is less than me so I'll stop right there so in this case 4 includes this yes yes yes so this is the entire width that I'll have right just 3 this part 1 this one yeah oh yes you're right it's the same height so I'll include that as well so basically I have a width that is one two three four four and five five minutes and the height would be three so three times five is fifteen so that would be the max area that this particular rectangle would make right so I'll do the same thing for all of these and then I'll keep updating the max the global max as um as I'm going through it but obviously that method will be over N squared time complexity so perhaps is it there's a better way to do it so let's see how we can do it in a better fashion now let's say I am in training through this histogram I start from index 1 so what – what my goal is is that I don't want to iterate through the entire array for every single index I just want to trade through it once and perhaps store some values that I would deem are necessary so let's say I'm starting with the first or the first value or the first index and I see I say that okay the next index or the value of the next index is greater than or equal to itself if it is then I know that I'll be able to expand my rectangle into it yeah right so I'll just keep going till the next value is greater than or equal to myself okay so and then throughout the time let me also record or keep a log because I just want to trade through this array once right I don't want to go back so let me just keep a log of all of the ones that I've already visited so I'll say ok index 0 as I have duplicates over here you know it doesn't really make sense for me to log values so I'll log the indices so I'll say ok I visited index 0 and I'll just keep doing the same thing I'll claim this letter as long as the next value or the next height of the bar is equal to a greater than the current height of the bar so I have 0 1 2 3 four so zero one two three and four right and then when I go to five I know that the height drops so I stop right there because obviously five can't include the three rectangle in its area because this thing is all right right the first bar can't go any further right yes exactly so let me just erase this make it cleaner okay so we are over here right let's let's say we stop right there right and I have this these are the bars that we already encountered on the way so when you stop right here perhaps this is a good opportunity for us to say okay let me just calculate the area that this bar would make yeah so the way we can do it is we can say okay let me start from this point and let me go to the left one unit so that I can cover myself right and I know that the one the bar besides me to the left which is this one it's height is less than myself it may even be equal to myself you know so perhaps in the first iteration you know let's just assume that the bars height is less than myself if that's the case I'll say okay let me just go one unit so this width is one in the height is 5 and my max right now I'm just keep along over here the max area is five now let's say so I don't want to compute anything twice right yeah so I computed the area that this rectangle can make or this this bar can make and I will take that out of my array you know just to say that I'm done with it now I'll say okay let me move further so this bar is done right let me just put a cross over there that bar is done now I move further but I still encounter three that is less than now whatever bar is at the end which is an index three witches a fight for so even for can't extend itself so I apply the same logic as we are over here you know this is the anchor point and we know that all the bars to the right of 4 is out of this alright Ken are the height of them is equal to a greater than 4 right so they can be included in its area so that problems that okay let's start from here and let's go till how far can we go I start over here and then I want to go till whatever is before me right I don't wanna because this is my point so I want to go till whatever bar is before me and get that width and then multiply with my height and I have the area that this bar can make right yeah so let's do that so this is 4 times 2 which is 8 so now this is a new maximum so I update that to it right so now I have the area of this rectangle basically right yeah yeah I'm done with this guy now I'll go further the next one in line that we haven't computed yet so we're done with these two we don't care about those anymore so next one in line that we haven't computed yet is 3 so as I move forward in my iteration I need to make sure the next one is 3 or less than 3 so this one is 3 so it's ok you know I can I can keep stepping up basically in our in our metaphor and I can keep climbing the ladder in my array yes so I can keep in yeah exactly so I can I can include this bar into this bars rectangle right so let me just add that over here and the same thing with the other three so actually this is the index yes is indexed so 0 1 2 3 4 5 5 and then I'll include 6 as well now when I encounter the next one so now I'm done with these two indices right now I'm over here I see that it's going back down this bar can include this one in Syria so I'll anchor myself right there okay I want to stop there and then we'll do exactly the same thing you will say that okay now let's take care of this guy first and see what smack Syria they can make the max area it can make is in this case starting move from the inker going all the way till whatever is before it right because we know that we want to stop at whatever is before it because that can be less than itself yeah so we start over here so this is what 3 times 1/3 it's not greater than max so we we ignore it right at the same time I take this out now I'm over here same thing I can't iterate any further so I need to compute the area of this bar or the the rectangle that this bar can make so same thing my anchor is still over here yeah and I say okay let me go all the way till the rectangle that was before me in this case it's this one so let me just take these two out or the bar yes the bar that was before me so in this case it's a 1 in index 2 which makes total sense right because these two are greater than 3 so obviously this guy will be able to extend into them but as far as our logic goes over here we these are like not even there right we were done with them actually right exactly exactly so everything everything to the left in my record is still less than or equal to the height of my current one so then I say ok let me start here and let me extend this to all the way there right right before my my previous element so then I'm talking about this rectangle here so this is what 1 2 3 4 times 3 which is 12 so I'll update my max right so then I'm done with this guy yeah and I am at 2 now so obviously I can't include this one now right because I can oh sorry it's 3 yes this is not the value so I can't include two yet this is still 3 so I say I do the same thing I started the anchor and I go all the way till the index 1 right and I say okay what is the area over here so this is 1 2 3 4 5 5 times 3 is 18 5 times 3 is 15 so the max will be 15 now right yeah and I'm done with this guy by the way as I'm going through this I'm only concerned with the last index of this array so probably should have used the stack so then put in the implementation I'll actually use a stack and not in the right so so this this guy is done right so now I'm looking at this one so obviously I can include this because this can encompass this in this rectangle so I'll say ok 6 & 7 so these two are done right so let me just erase them and this one's done as well okay so now now I'm done actually now I don't have any more right I can deter it further so I stop right there and then I have some stuff left in the in the array or now it's a stack let's say let me just make it a stack right so I have 1 0 1 & 7 so I say so these are the bars that I have yet to calculate rectangles for right so so I start at index 7 which is this bar I say okay let me calculate the rectangle for that one say okay in order for me to do so I'll need to anchor I'll need to anchor my my my right my right point onto the index after me right it'll probably be at the length and I need to go all the way till this one so I need to stop right there right yeah so I'll have one two three four five six and seven one two one two three four five six yes I'll stop right there so I'll have six six times two is twelve it's still not greater than 15 so it's okay but I'm done with this right now I have one left so the the number index one so I do the same thing I calculate it's rectangle so it's basically from here still the anchor point remains the same all the way till there so this is what six times 2 or 7 times 2 1 2 3 4 5 6 7 7 times 2 that is 14 still less than 15 yeah same thing over here this will be what yeah 1 times 1 times 8 which is 8 so it looks like the max is going to be 15 yeah it looks like this implementation works and also it's just linear time complexity because we're just iterating to this array once and we have stack on the side but we're not really going through all the elements at any given point in time so if you don't mind let me try and transform this logic into into actual code okay so let me erase this erase this as well all right so let's say I have a function let me actually erase this as well let's call it max area and let's say it takes in a histogram so the first thing I would want to instantiate is a stack right so I'll say stack and obviously this is pseudo called stack equals new stack and at the same time I want a global maximum to keep track so I'll say max area actually I already call it max area so let me just call it max our function is max area right yeah max equals zero initially and to iterate through this array as we're anchoring at certain points you know I would use a while loop because I want full control over when I'm incrementing the index and I wanted to be automated so I'll say initial index equals zero and then we'll go into the while loop so I basically say while I is less than hist dot length you should do this now what should we do well if the if the stack is empty then we should push whatever is the index so we shouldn't actually push the values just like I did over here we should push the indices so I'll say if stack dot is empty it's true so is there any other condition when we would push it we would also push the index when it is greater than whatever was index before it right so I would say or if stack dot let's see how would we yeah so if we would say if stack dot peak right so the current index that we have at the top of the stack it should be less than or equal to so it's less than or equal to the value at hist I right yeah so this is the case then we add the element or the index into our stack josè stack dot push high right and we will also say I plus Boston yeah so this concludes this if statement but if this is not the case then as we saw over there what we do is we start computing the area and also we don't just compute the area but we pop it out of the stack right so let's do that else we say let's call it current so at this point the the bar that we are at will be the maximum of all of the bars that we have encountered or of all of the bars that are in the stack right yeah so let's say cur max let's call it car max or her highest you know car max okay let's at Carmack's equal stack dot pop so now I would have popped it so I've I know what its value is right or I can get its value from the histogram all right and then what I do is I would need to compute the area yeah right so at this point I have already incremented I right in the in the previous iteration in the previous iteration I had already incremented I so the way I come here is by checking that hey actually the histogram value at I is greater than my topmost value right so the eye that is the index of Carmack's it will be actually one less than that all right it'll be I minus one so in order for me to compute the area let me just call it area equals I would need the I would I would need the height or basically the value at Carmack's so I'll say hist per max times I would say whatever I is minus one right whatever I is minus one so that would give me the index of this guy right there if this is the current max basically and then I would want to go all the way to my previous number in the stack right so I would say – stack dot peak right so what if if there are no elements in the stack then I would I would just not have this one right I'll just have I minus one so in this case let me actually put that in I would say times stack dot is empty if stack is empty or let me call this if stack is empty then we would say that it should be times I minus one right we don't go all the way but if there is something they will say I minus one – stack dot peak right yeah perfect so now we will have the area and then we'll just do a comparison that if area is greater than max max equals area right yeah so this actually concludes this value so we'll go through all of them at the end we will have some bars left that we haven't computed the the area for so we will have to pop you know all of those so let's do another while loop so we'll say while exactly yeah so I basically say while stack is not empty and I'll keep popping so I'll say while stack dot let's say well stag peak you know well there's something in the stack keep doing this so what do we do we do we actually perform the same logic we will say car max equals stack dot pop right let's say area equals the same computation hist car max times their ternary operator stack that is empty hi – one else hi – one – stack dot peak right yeah and then the same conditional so if area is greater than max max equals area and that concludes a while loop and also includes our function oh yeah we should also return the my next value at the end we didn't do all this work for nothing so I'll say it in return max thanks for watching guys if you like this video let me know by hitting like button below and next week I'm actually giving you the option of choosing which problem I should cover so the first one is should I cover n Queens where you need to place n Queens or n number of Queens on a chessboard such that none of the Queen's are attacking each other or the second one is 0-1 knapsack it's actually a very popular problem with dynamic programming so let me know in the comments below which one you would like me to cover and I'll see you next week

Why is this a linear time algorithm (O(n))? Isn't it a worst-case O(n^2) algorithm? For example, the histogram 1, 2, 3, 4, 5, 4, 3, 2, 1. We just count your backtrack numbers: At the 2nd '4', you need to back track 2 steps to previous 4, At the 2nd '3', you need to back track 4 steps, etc. The total of your backtrack steps is 2 + 4 + 6 + 8 + … + (n-1) (When we have [n/2]+1 in the center rather than 5 in this case). Thus you need at least O(n^2) in your backtrack steps.

21:08 you already put an if to act when the stack is empty. then why r u checking it again on the else?

this video is great b.t.w

One minor correction, if the stack is empty,

int area=hist[currMax]*i

good job

Nice!

Very nice video

In the case that stack is empty, it the width is "i" not "i-1"

finally understood after watching your video..thanks

I think There is a way t do it by thinking that finding the same height and adding all the number of bars you have crossed and then finding the area of the rectangle that you have identified and doing it until max area is obtained

i think this works too (in python):

ar=[]

R=[]

x=0

while True:

try:

x=int(input(": "))

ar.append(x)

except:

break

for i in range(1,max(ar)+1):

t=0

for k in range(0,len(ar)):

if ar[k] < i:

t=0

continue

R.append((t+1)*i)

t=t+1

print(ar)

print(max(ar))

print(R)

print(max(R))

it shouldn't be stack.peek()<=hist(i), it should be hist(stack.peek())<=hist(i)

Very nicely explained, thank you!

Subscribed! Really explained this question well. Please keep the good work.

Not a great explanation. A mathematical proof should be provided for the arithmetics of the problem. Still don't understand a lot of things.

how about [2,12]?it seems not work .

package com.coding;

public class Histogram {

public static int findMaxAreaInHistogram(int[] hist) {

int areaMax = 0;

int len = hist.length;

if (len <= 0)

return areaMax;

int[] area = new int[len];

int i = 0, min = 0;

boolean backarea;

int backcount = 1;

while (i < len) {

area[i] = hist[i];

min = hist[i];

backcount = 1;

backarea = true;

for (int j = i – 1; i > 0 && j >= 0; j–) {

if (hist[j] < hist[i]) {

if (hist[j] <= min) {

area[j] = hist[j] * (i – j + 1);

min = hist[j];

}

backarea = false;

} else if (hist[j] == hist[i]) {

if (hist[j] <= min) {

area[j] = hist[j] * (i – j + 1);

min = hist[j];

}

if (backarea)

backcount++;

} else {

if (backarea)

backcount++;

}

}

area[i] = area[i] * backcount;

i++;

}

for (i = 0; i < len; i++) {

if (areaMax < area[i])

areaMax = area[i];

}

return areaMax;

}

public static void main(String[] args) {

int[] hist = { 1, 3, 2, 1, 5, 4, 5, 4, 2, 3 };

// int[] hist = { 9, 8, 7, 6, 5, 4, 2 };

// int[] hist = { 1, 2, 3, 4, 5, 3, 3, 2 };

int maxArea = findMaxAreaInHistogram(hist);

System.out.println("Maximum Area : " + maxArea);

}

}

I tried various input histograms for the shared video, many of them are failing…

So I have given the First Attempt for given problem… however this solution is not linear.. working on it for same to bring it to Linear ….

Won't work for bimodal

How i get your previous problem?which were send by you in email.

he things he is that guy from mit. this young indian otherwise i cant understand why he needs to talk to another person in the room

This is a bad final solution. You could have instead had 2 pointers, one at the starting index and another at the ending index. As you move these pointers, you save the largest area gained, and the two elements you multiplied to gain this largest area. You will move only one pointer at a time, depending on which pointer has a smaller height value. You can stop moving both pointers and return you final data, when the pointers go past each other. Worst case run time of O(n). Now you don't need a stack and this has a faster run time.

for videos like this you should probably step away for at least a few seconds and let the viewer see the white board…. you're blocking the code in all the ending shots

Hi, Irfan.

Thank you for the task and the proposed solution based on using a stack.

However this problem has a simpler solution (one can easily calculate the "next" rectangle from the previous one)

This actually fails for a histogram of – 5,5,5,5,1,1,1,1

You just did a damn good job of explaining everything so intuitively. Just after watching your explanations, I go and write code directly for a problem without hesitation, and it would work right away ! Please continue making videos, I'm very sure there are no people on YT who explain things this well.

Hey Man! …….. your teaching process is gr8 !

it looks from code that pushing onto stack will happen only once as long as the condition meets(as in example, it will happen in the beginning ), but at the time of analysis we have seen that pushing on to stack will happen two times(for bars with index 5, 6) , any clue??

BEST on whole INTERNET!

Nice explanation 🙂

Correction – "hist[stack.peek()] <= hist[i]" in place of "st.peek() <= hist[i]" and

s.isEmpty() ? i : i – 1 – s.peek()

Great Video. You earned a subscriber in just one video. Your videos are really fun to watch at 2x.

Although it should be just i instead of i-1 when the stack is empty while calculating area.

Does this approach works for 2,1,2 histogram ??

This should return 3 as a max rectangle area but with this approach, its coming as a 2…

Awesome explanation! can you do a video for Painters Problem or Kth number found using Binary search only

The index of the code is wrong, cause we have increased i to the next value(which is smaller than the currMax), thus if the stack is empty, the width of it should be i(beacause the currMax's index is i-1, the width of it is i -1 +1 which is i, we count index from 0, that's why we need to add 1)

Another great video. Subbed & really looking forward to working through all the vids on your channel

this best video on the You tube on this problem …. you need more subscribers … thanks !!!

toooooo goooooood bro welll work…

Hey, your code has a major issue? Try running it for 2 2 2 2 2, your code will give output as 8 while it should be 10. To avoid this define area like this-

int area=(st.empty()) ? hist[currMax]*i:hist[currMax]*(st.empty()? i-1:i-1-st.top());

Very nice explanation thanks a lot:)

who is the interviewer… she is pretty awesome!

I really like the way you let us see you talk through the problem in these vidoes. Thanks! Question: Are you sure the single stack implementation you're using is O(n)? I think in the worst case you have steadily climbing bars, so every element looks through every other element (ie: while(stack.peek())?

here's how I'd do it

function largestRectAreaInHistogram(arr) {

return Math.max(…Array(Math.max(…arr)).fill(0).map((_, row) =>

arr.filter(value => value >= row).length * row

))

}

Superb!

how to store dimensions of the max area rectangle.

if(stack.isEmpty || hist[stack.peek()] <= hist[i]) – we are working with indexes

great video, really helpful