Largest rectangle in Histogram | Leetcode #84
ฝัง
- เผยแพร่เมื่อ 11 ก.ย. 2024
- This lecture explains a very popular programming interview question which is to find the largest rectangle in histogram.Given an array representing heights of each bar in a histogram, we are required to find the area of the largest rectangle which can be formed from the given histogram.I have first explained the problem using some insightful examples and then i have shown the most important observation for this problem.Using this observation, I have shown an algorithm with optimization using stack which can find the largest rectangle area in the histogram in just O(N) time using just 3 traversals.I have also shown the dry run of the code along with code explanation at the end of the video.CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
========================================================================
Join this channel to get access to perks:
/ @techdose4u
INSTAGRAM : / surya.pratap.k
SUPPORT OUR WORK: / techdose
LinkedIn: / surya-pratap-kahar-47b...
WEBSITE: techdose.co.in/
TELEGRAM Channel LINK: t.me/codewithT...
TELEGRAM Group LINK: t.me/joinchat/...
=======================================================================
CODE LINK: gist.github.co...
USEFUL LINKS:-
Implement min stack: • Implement min stack | ...
Implement stack using heap or priority queue: • Implement stack using ...
**Similar Questions, Monotonic Stack**
239. Sliding Window Maximum
496. Next Greater Element I
739. Daily Temperatures
862. Shortest Subarray with Sum at Least K
901. Online Stock Span
907. Sum of Subarray Minimums
687. Delivering Boxes from Storage to Ports
Thank you!
trapping rain water is mostly similar also
Thanks Buddy :)
thank you :)
85. Maximal Rectangle
Best explanation on TH-cam, many people simply showed the code instead of explaining the logic.
Thanks man :)
Yes agreed neetcode and techdose are two beautiful channel
Bro do u have code of this problem?? In C longuage
If I ever get selected in a Tier - 1 company. This channel would be having a big contribution to that.
Means a lot ❤️ I wish you do
Best explanation on even why brute force works which no other channel was able to visually explain so well. Brilliant job keep doing more such videos for hard problems!
Thanks :)
This is definitely the best explanation i could find on the internet. This guy showed how to solve it instead of just showing problem solution.
😅
Of 4 videos I watched about this problem, this is the best. It describes the problem, builds up the required intuition and shows a real chain of thoughts that from the brute force approach leads to the optimal solution. Congratulation. Great job!!
Thanks :)
I think no one else can explain better than you. Problem was very overwhelming in the begining but at the end of 27th min I felt how patiently and clamly you made it clear with making my head hurt :) Keep making similar video. Really appreiciate your hard work
Thanks :)
It was hard to find video which explains the intuition behind the solution to this problem. And this channel always gets it right.Very good work.
Btw, the max area calculation can be done when calculating the right limit array for each bar, so we need 2n traversals only.
🤗 Right
I watched other channels for the same question but couldn't not understand clearly. But this is best explanation video for this question. Best part is the you start with brute force approach which is more important than directly moving to optimal one.
😊
The way u explain step by step and reaching from brute force to optimal is awesome !!✨ Thanks ♥️
Welcome :)
Your videos have helped me to a great extent. Recently I got placed at Barco systems as Software Engineer.
Wow great ❤️ Congratulations 🎉
I was struggling with this problem for a quite long time because I was not able to understand the intuition behind it. Thanks to techdose for clear explanation of the intuition
👌🏼
best explanation with all given logic I did not understand this problem solution with paid course but Because of you sir I understood thank you so much
Welcome 😊
I just wanna thank you, because this is the best explanation on the planet for this problem.
Top notch explanation i just coded it myself after your explanation, keep doing the good work.
People are showing steps of algorithm without explaining anything....
This is a gem of video which clearly explains the 'why' of algorithm.
great job.
btw, I see another solution in Leetcode with one loop, is it similar to this one? I dont understand that one loop solution.
No need to overkill a problem if you can solve in same time complexity :)
@@techdose4u I understand that the time complexity is O(n),but during interviews some idiot interviewers will ask a follow-up question like 'hey can you do this without traversing the loop twice?' 😂
This is the perfect explanation , I have ever heard of , Hats off ! sir
Thanks 😊
I love how you walk through each and every step, which helps to sink in the algorithm and helps to clarify things I misunderstood or missed. Keep up with the good work!
How do you only have so little subscribers and views? You're doing an amazing job with these explanations
Thanks 😊 Share in your contact 😜
I have tp say this is the best explanation among all the posts! Thank you so much for sharing!
Welcome :)
Amazing, just amazing, after 4/5 videos, this is the only guy that makes sense!
thanks :)
Saying from my down to heart it is the best explanation in youtube for this problem..Hope tech dose and Take you forward alone enough to getting placed in faang like companies..
Brilliant. Love the appoach of going from brute force to optimal. Love the step-by-step explanation and running through of the algorithm.
Thank U so much man, plz dont stop making videos if u ever think views are less
Welcome :)
This is phenomenal. Couldn't find a better explanation than yours.
Thanks a lot sir 🙇🙏.
Best vedio I have found on TH-cam on this topic. You explained each and every bit of problem clearly. Thanks again.
Welcome
probably my first comment to a youtube video ! Keen and neat explanation for this problem .Thanks a lot
Thanks :)
this channel is better than (All the combined paid edtech), thank you very much
Welcome :)
The best channel in TH-cam thankyou techdose
Great explanation but some of the slides have some pre-existing values which don't fit the current example. The presenter strikes out those unmatching values and writes the correct ones next to them. It would be easier to follow if there were no such pre-existing values from a different example.
I have watched many videos on this problem but couldn't understand anything . Best explanation on youtube !
Thanks :)
Phenomenal stuff. You can explain really well. Thanks.
How do you know the explanation is amazing?
After watching the explanation (without looking at the code), you write the code and it passes from the first time.
😀
Can you please tell how to intuitively prove the time complexity to be O(n) for this problem? Does pushing and popping not contribute to greater time complexity?
pushing and popping in stacks takes time complexity O(1). And as we're traversing through the given array once, the complexity became O(n).
@@ferozmohammad5841 In order to build the stack, there's a "while" inside a "for". Shouldn't it be O(n^2)?
The worst-case scenario happens when the bars are strictly decreasing and it's O(n^2) IIUC
No one explains it better :) Thank you
Welcome :)
best explanation on whole yt
Best Explanation ever on the YourTube.
Thanks :)
But popping from stack might need O(n) and traversal from left to right and right to left requires O(n), hence the total complexity should be O(n^2), right ?
your explanations are better than 20k rs paid courses' teachers.Thanks a lot
much more complicated...but much more easy to understand.......thank you
Welcome :)
Here is Java soltuion :
public int largestRectangleArea(int[] heights) {
// clue is we have to include the bar completely in the maximum rectangle
// we have to calculate for each bar, the area with width to the left and width to the right
// width to the left will be the smaller bar index to the left of the current bar
// lly width to the right
// to optimize the time to calculate width , we use stack
// if no smaller to the left , then put 0
int left[]=new int[heights.length];
int right[]=new int[heights.length];
//stack to push indexes
Stack stk=new Stack();
for(int i=0;i= heights[i] )
{
//keep popping the elements till the smaller element is reached
stk.pop();
}
//if stack is empty no smaller element to the left
left[i]=stk.empty() ? 0 : stk.peek()+1;
stk.push(i);
}
}
//now empty the stack
while(! stk.empty())
stk.pop();
// lly for right
for(int i=heights.length-1; i>=0 ;i--)
{
if(stk.empty())
{
// that means no element to the left, put it as 0
right[i]=heights.length-1;
stk.push(i);
}
else
{
while(!stk.empty() && heights[stk.peek()] >= heights[i] )
{
//keep popping the elements till the smaller element is reached
stk.pop();
}
//if stack is empty no smaller element to the left
right[i]=stk.empty() ? heights.length -1 : stk.peek()-1;
stk.push(i);
}
}
int max_area=0;
for(int i=0;i
Thanks for sharing 👍
best explanation i can find on the internet for this question.
great explaination for every sticky points
😊
Thank you! I thought I could use a monatonic queue but still could not figure it out. You explained it very clearly
Welcome 😀
The best explanation on the internet.
Thanks :)
Best Explainatin ever👍
Best Explanation !!
Thanks:)
Bro plz include manachers algorithm
I have been suggesting tech dose to all of my friends juat bcz of the great content ... Good job
It will come someday :)
This is very nice video and explained the problem in more simply way.
int hist[] = {1,4,9,5,7,2,10,3,5};
OutPut : 16
I tried to run this program using the same logic for the above array. But not able to understand why it's giving 16 as an output.
I think it should be 10*3=30. Correct me if my understanding is wrong
Good video
Finally in this channel i understood the solution. what about space complexity? i assume it's O(N). correct me if i am wrong.
won't popping the stack with a while loop increase the complexity to something greater than O(N)?
Awesome explaination🤗🤗 Bhaiya
Thanks
Life savour, for beginners like me. Thanks so much!
So technically we can say this problem is a modification of trapping rain water problem, right?
no,they are different
Great explanation
no one like u on TH-cam , you achieve one subscriber
Great work man
i feel that the only way it is possible to answer 1 or 2 of this difficulty of question in a coding interview is to have already solved it before that day.
Great explanation sir.... the ways you explain is pretty awesome... very helpful.. thank you for such a great tutorial
Welcome 😀
Brilliant! Great Explanation.
Thanks :)
You saved my life with this video, thank you very much :D
Great ❤️
i can't understand why time complexity is O(N) in case of stack , in worst scenario it should be O(N*2)
I had the same thoughts. It's a while loop inside of foreach loop.
thank you soo much bro; you earned yourself a lifetime subscriber :)
Excellent explanation 🙏🙏👍👍
Thanks
@@techdose4u it was a hard level question but you made it very simple with step by explanation with dry run of example which is awesome, I've recommended this content to all my friends
How is this O(N) in the solution with the stack, when we're foreach-ing over all bars (O(N)) but then _internally_ also while-ing through the existing stack and popping (times another O(n))? Isn't this a straight O(N^2). They are clear nested loops to me.
Nested loops don't mean O(N^2). How many times the stack will be filled and popped? 2N at most! So, 2N for the inner while loop + N for the outer loop = 3N = O(N) time complexity.
Very well explanation , Thanks a lot it helped me a lot. Specially liked the fact that even the brute force was explained.
nice explanation brother...
I was asked this question in my interview of meditab ahmedabad company.
i did this with pair but now i think i there is no need to use pairs, but i do suggest to use vectors instead of arrays
class Solution
{
public:
vector second(long long a[], int n)
{
vector v2;
stack s;
for(int i=n-1;i>=0;i--){
if(s.size()==0){
v2.push_back(n);
}
else if(s.top().first=a[i]){
s.pop();
}
if(s.size()==0){
v2.push_back(n);
}
else{
v2.push_back(s.top().second);
}
}
s.push({a[i],i});
}
reverse(v2.begin(),v2.end());
return v2;
}
vector first(long long a[], int n)
{
vector v1;
stack s;
for(int i=0;i
Grt explanation
Thanks :)
very good explanation
very nice and swift explaination keep up the good work👍👍
Thank you for explaining it very well. Can you tell if there is any dynamic programming involved here?
We can reduce on more traversal by doing max area in the second one itself
Nice one
Best explanation !
Great explanation, can you please make a video for the problem 1504. Count Submatrices with all ones
I will try
I will try
In your code, the problem can be solved using 1 array by calculating the maximun area in the second for loop instead of assigning the value of right limit.
Yes right. But it will make harder for some people to understand 😅
@@techdose4u But your explanation is way much better than anyone.
Thanks. But I just keep in mind that if you are watching the video then probably you might have missed some concept and explaining from ground level makes understanding simple. Later you can build your own optimisations when you know basics. Because everyone has their own way of building :)
So much clear explaination. Thank you very much :)
great explanation
Good explanation
you saved my life
😂
Very helpful video!
Thanks for detailed explanation. Keep up good work.
Thank you so much! Really helpful explanation :)
Welcome :)
best explanation ever......
Thanks :)
tanks a ton for such good explanation
Superb explaination 👍
the explanation is just the best!
Thanks a lot for our videos
Great explanation. But how can someone come up with this approach in 30 min interview and also code it?
isn't it O(n^2) because there is loop in a loop for finding left and right bars??
Same question.
Thank you so much sir
really helpful
Welcome
clear explanation
Awesome explanation 👍🏻
Thanks 😊
Why is the complexity o(n) for filling left and right array
Co it's one traversal operation :)
You very well explained how to do it, but you didn't explain why to do it & what should be the approach, how do u come up with the observation etc :(
You need to practice these to get the intuition.
you are the best
Thanks 😊
Superb explanation!!
Cheers man!
Thanks
Amazing Explaination
Thanks 😊
Keep it up