Coding Interview Problem: Largest Rectangle in a Histogram

Sdílet
Vložit
  • čas přidán 1. 06. 2016
  • Episode 05 comes hot with histograms, rectangles, stacks, JavaScript, and a sprinkling of adult themes and language. Brace yourselves!
    Full text-form code is available here: jg.gg/largest-rectangle-in-a-h...
  • Věda a technologie

Komentáře • 314

  • @Jeff.Wilson
    @Jeff.Wilson Před 3 lety +10

    It's very hard to come up with the optimal algorithm when you hear this problem for the first time on your interview. People who are giving this question on the interview and expect to get an optimal solution, shouldn't be performing interviews at all.

  • @pspsora
    @pspsora Před 7 lety +31

    i need a t-shirt that says "function popThatShit(){}"

  • @brandonm1088
    @brandonm1088 Před 7 lety +13

    I was amazed for the longest time on how you write so well mirror until I figured you most likely are not left handed. Really clever presentation!

  • @HughGuiney
    @HughGuiney Před 7 lety +38

    DID ANYONE ELSE NOTICE THE INDIVIDUAL CHARACTERS FALLING DOWN FROM THE BOARD AFTER HE SPRAYED IT AT THE END??? 15:52

  • @Shaddymaze
    @Shaddymaze Před 4 lety +2

    High quality all around. Well done, sir! You just earned yourself a sub.

  • @albertoesquivias6073
    @albertoesquivias6073 Před 7 lety

    just found your channel, its awesome! keep being yourself and hopefully you upload more soon. thanks!

  • @thequantartist
    @thequantartist Před 4 lety

    Just discovered, this channel. Simply love it!

  • @justingivens217
    @justingivens217 Před 8 lety +1

    Awesome explanation of problem and solution! Keep them coming!!

  • @manusharma5817
    @manusharma5817 Před 3 lety +1

    probably the best explanation on CZcams even today. Thanks, man.

  • @MaxHeckelIsMe
    @MaxHeckelIsMe Před 8 lety +2

    Great video, going to binge watch the rest now.

  • @aditya070791
    @aditya070791 Před 6 lety

    Loved the video ! Infinitely more interesting than other ones out there.

  • @sgtoverload_5167
    @sgtoverload_5167 Před 5 lety

    awesome stuff man, keep up the good work i really like your thinking style..

  • @Virtualexist
    @Virtualexist Před 12 dny

    This was 8 years ago? Bro was way ahead of his time!

  • @vanjajaja1
    @vanjajaja1 Před 5 lety +7

    “i, like most people who work in java, dont know java.” i can relate.

  • @TheJohn6866
    @TheJohn6866 Před 7 lety +3

    Could you please explain the case when there is just 1 bar at position 0? I think the maxarea should be 1 but your code would return 0 since pos and tempPos would both be 0.

  • @chicken6180
    @chicken6180 Před 7 lety +1

    "Uncut Jackson... unrelated to my parents decision"... SO subtle but i had to listen again to see if that was what I thought it was

  • @asdfghjklqwertyuiop7899
    @asdfghjklqwertyuiop7899 Před 7 lety +1

    love your style. pls keep making more.

  • @crankyinmv
    @crankyinmv Před 3 lety

    Thanks for this. I love seeing a solution in JS. I managed to do this problem using a tortured DP-ish solution which kept track of rectangle areas and heights. Nice to know there's a sane solution.

  • @StockDC2
    @StockDC2 Před 7 lety +2

    Hey, thanks for the video.
    I have a quick question if you don't mind. When you went from 3 to 2, you only popped the top value from the height stack (since the rectangle at index 2 started from index 1). However, when you go from 2 to 1, you pop from both stacks. Can you explain why? From my understanding, there is still a rectangle from index 1 to index 3 with height 1.
    So what I have in the Position and Height stack when i = 5 is:
    P - H
    4 - 2
    1 - 1
    0 - 1
    Thanks!

  • @arjunkashyap8896
    @arjunkashyap8896 Před 4 lety +16

    6 seconds into video: "Wait am I watching a coding interview tutorial ?!?!"
    Data Structures and Algos are such complex and mind numbing topics.
    I love the fact that you added humor to such complicated topics. Its good to be laughing while learning. It just made learning a lot more enjoyable.
    SUBSCRIBED

  • @HardCapGamingOfficial
    @HardCapGamingOfficial Před 7 lety +4

    I laughed so hard when he named the function popThatShit xD

  • @pradeepravi7591
    @pradeepravi7591 Před 7 lety +10

    Dude ..thank you so much... I completed this problem ... :-p
    < Your Largest Rectangle submission got 50.00 points. >

  • @bob84409
    @bob84409 Před 7 lety

    Great job on the video, thank you for making this!

  • @MrNargleflex
    @MrNargleflex Před 7 lety +3

    Hey this video rocks! I had been puzzling for a while on how to do this, and the best I could do while getting a correct answer was O(n^2) time complexity, which is garbo. Thanks for the great explanation!

    • @DarcMagikian
      @DarcMagikian Před rokem

      Is this not also O(n^2)? since there's a while loop inside a for loop?

  • @michaelcoppinger786
    @michaelcoppinger786 Před 8 lety +4

    Really great vid! Like how you keep the problems interesting and offer entertaining and clear explanations. Enjoy your work a lot :)

  • @bokonon88
    @bokonon88 Před 7 lety +1

    after processing index 3, how is the 1x(4-1) rectangle of height 1 starting at position 1 ignored?

  • @deepaligarg7643
    @deepaligarg7643 Před 2 lety

    Very nice. The code works. Thank you so much for making this video and explaining it so very well.

  • @bennettbmadavana7176
    @bennettbmadavana7176 Před rokem

    Thank you so much
    was stuck on this problem for days, finally clicked ✨

  • @EvanKozliner
    @EvanKozliner Před 4 lety

    This question is wild. Awesome explanation :)

  • @RaviKumar-vk6ib
    @RaviKumar-vk6ib Před 4 lety

    It was awesome experience...didn't get bored for a sec...please keep up this swag!!!

  • @TheTwilightHero
    @TheTwilightHero Před 8 lety +2

    Really loved it!

  • @reyou7
    @reyou7 Před 5 lety

    That's how I do interviews, walk in the room and say "hey, what's up motherfuckers?"

  • @ExtinityOfficial
    @ExtinityOfficial Před 7 lety

    Just got a something new in an interview i haven't seen before. Find the amount of magic squares in a given rectangle 2d array. Took me a while to figure out the optimal way to do it

  • @g00dvibes47
    @g00dvibes47 Před 7 lety

    "...getting a little bit bored with the polite, PC...."
    subscribed.

  • @dubeya01
    @dubeya01 Před 8 lety

    Very well articulated! Keep it up

  • @TheSexGod
    @TheSexGod Před 4 lety

    amazing explanation. do more videos like this!

  • @programminginterviewprep1808

    I am wondering how did you take this video? It looks very interesting!

  • @sajanchoudhary108
    @sajanchoudhary108 Před 5 lety

    Finally, someone has succeeded in explaining this question.

  • @ON-ne1rd
    @ON-ne1rd Před 5 lety

    What happens if you replace the tempPos logic with pstack[-1]+1 when stack is not empty and let it be zero when stack is empty? Basically I am thinking the tempPos logic may be redundant. Am I wrong? In what cases does this not work if it doesn't?

  • @sdddyr
    @sdddyr Před 8 lety

    Awesome video, tried it in C# and works nice !

  • @motocomputer
    @motocomputer Před 3 lety

    this is such an amazing explanation

  • @ranzort
    @ranzort Před 4 lety

    All your vids are so good I have learned to tolerate bad BGM

  • @Milkyboy92
    @Milkyboy92 Před 8 lety +2

    Cool video! As a general idea for avoiding popping that shit at the end, you could insert a 0 at the end of the histogram. Or is this too hacky?

    • @DiogoNeves
      @DiogoNeves Před 7 lety +1

      That's interesting! I'd guess explicitly popping is more... explicit and clear. Can't wait for more opinions/logic on this :)

  • @SephirothITM
    @SephirothITM Před 7 lety

    Did you leave it to dry for a while before you cleaned it at the end? The letters don't drip, but they move in tact... weird effect.

  • @snejati86
    @snejati86 Před 8 lety +50

    Make some promises and you might get your callbacks .... I'm sad about this joke.

    • @jackson-gabbard
      @jackson-gabbard  Před 8 lety +9

      That's not a joke I made is it? I agree that it's awful.

    • @stasvpavlov
      @stasvpavlov Před 7 lety

      Sina Nejati I can tell that you are probably a really l "fun" guy.

    • @bhaumin
      @bhaumin Před 6 lety

      I await'ed at a sink

    • @iveted4738
      @iveted4738 Před 3 lety

      @@jackson-gabbard dude why'd you stop making these videos?

  • @arpanpandey7854
    @arpanpandey7854 Před 4 lety

    dude u r hilarious ! keep the good work up !

  • @Bdjdiwhbkdk
    @Bdjdiwhbkdk Před 7 lety +5

    I have a question. This is obviously a coding interview problem, so you need to code the thing. But what if using stacks isn't the "obvious" method, and just talking your way through and using stacks is confusing to the interviewer? You'd obviously want your interviewer to agree that your code works right then and there. You're not really gonna debug it and test if it works. So you might want to draw those stack diagrams and the histogram. But should you be doing this?
    When you're coding, is it okay to draw pictures to visualize your thought? And also, rather, SHOULD you be visualizing your thoughts during a coding interview?

    • @jackson-gabbard
      @jackson-gabbard  Před 7 lety +16

      In the interviews I've done, candidates who could draw a coherent visual to help them make sense of the problem tended also to write better code and explain their code better. If you can draw a visual quickly that puts you and the interviewer on the same page, I think that's definitely to your advantage. However, it's a matter of timing. If you spend 10 minutes diagramming, you're probably taking too long. 2 or 3 minutes, tops. Then focus on the code. Also, you totally should be debugging and testing mentally once you finish the code. Good question.

    • @revantnayar3408
      @revantnayar3408 Před 6 lety

      Jee B to

  • @TheJayRap
    @TheJayRap Před 7 lety

    wow this guy is so smart at cursing

  • @bheshgurung6946
    @bheshgurung6946 Před 5 lety

    The implementation fails for [2, 1, 5, 6, 4, 4, 3]. It does not check if the next height is equal after encountering a smaller height. For the sample, it returns 10 instead of 16.

  • @soumya5200
    @soumya5200 Před 7 lety

    How did you create a video that makes you look like you are writing on glass?

  • @sebastiansiatkowski3720
    @sebastiansiatkowski3720 Před 7 lety +16

    Your solution is correct, but the magical change at 15:45 is suboptimal - it can lead to having multiple entries for the same height at the top of your stack. For example input [1,2,1] leads to having [0,1] and [1,1] in your stacks at the end of the for loop. A better solution would be to add "|| h > hStack[hStack.length - 1]" to the if statement you removed.
    Just wanted to chime in since I just went through all your Coding Interview Problem videos while preparing for my coding interview. They were a great resource, thanks for all the effort you put into those!

    • @itizir
      @itizir Před 7 lety

      Was going to make a similar remark...
      In fact it looks like it would even potentially give wrong answers!
      Take [ 1, 2, 3, 2, 1 ]: the largest rectangle is 2x3 = 6, but with the given code, the two 2s would be counted as part of separate rectangles in the stack (of size 2x1 and 2x2), so the code would think the 1x5 rectangle is bigger. Eh.
      Or is it me who's missing something? :P

    • @itizir
      @itizir Před 7 lety +1

      Ah no indeed, I'm the one who missed something: the size is calculated keeping the very last index accessed, so it will indeed see the correct rectangle... My bad!

    • @sirnawaz
      @sirnawaz Před 6 lety +1

      @Sebastian: Wow.. I was thinking exactly the same thing.. and in fact, I corrected this part:
      repl.it/repls/WoefulFavorableCustomer
      And then I started looking for a comment, hoping that someone else (apart from me) would pointed out this.. and I found yours. Thanks for confirming that WE are right.

  • @arijiang7996
    @arijiang7996 Před 4 lety +1

    Really clear explanation with beautiful visuals (did you actually write in reverse???), I just find the bg music a bit distracting but other than that true awesome!

    • @ApurvJaiz
      @ApurvJaiz Před 3 lety

      I guess it would be a lot easier to just flip the video while editing.

  • @naythaniel
    @naythaniel Před 7 lety

    +Jackson Gabbard, JavaScript has Maps and Sets now (and WeakMaps and WeakSets), so not just 2 anymore. Although probably you knew that already.

  • @sureshchaudhari4465
    @sureshchaudhari4465 Před 5 měsíci

    Jason Stathum from action hero to Software engineering he learned everything huge respect :P

  • @MrDemianTV
    @MrDemianTV Před 7 lety

    They say you can grab a person's attention in the first 15 seconds of the video. You nailed it.

  • @ciphertester1147
    @ciphertester1147 Před 6 lety

    Jackson Gabbard, I can't seem to follow how you got the starting position for the 3rd bar with height 2, for example if you took away the first bar and you just have an array of histogram heights of 3,2,1 how would you know that starting point of say height 2 or height 1. I think you need to hold these values. I would create a hash map which has height as the key and increment it each of the key by one if it qualifies/valid or pop it and compare it to the max value. A good test case to consider is 3,3,3,2,1,2,4,4,3,3,2,0,3,3,3,2,2,1,1,1,1,1

  • @kunalsinghgusain2070
    @kunalsinghgusain2070 Před 6 lety

    great approach and great explaination i've seen so poor explainations. Yours is better than all others.
    i have a problem and i wish you could solve it in next videothat is "given a matrix of 0 an 1's how can you find maximum area rectangle?".

  • @lachlanhillman7469
    @lachlanhillman7469 Před 4 lety

    You don't need the heights stack. Just modify the original heights array with the new reduced height values.

  • @kristymayo494
    @kristymayo494 Před 6 lety

    I'm super jealous of your markers. I need blood markers in my life.

  • @sreekanthjujare
    @sreekanthjujare Před 3 lety

    I am curious how he created writing on the glass effect. Any one knows?

  • @takanashiouken
    @takanashiouken Před 4 lety

    Is it only me? No matter how many time I read this still don’t get how does tempH*(pos-tempPos) get the area?

  • @parthapratimmallik8354

    Cool... Loved your presentation...

  • @anolisporcatus
    @anolisporcatus Před 4 lety

    your videos are the bomb.com man! keep it up

  • @arunraj2527
    @arunraj2527 Před 5 lety

    Presentation + effort + explanation = +1 subscriber

  • @satang500
    @satang500 Před 4 lety

    Hi Jackson, your two stack approach is much easier to compute area.
    When I first see this problem, I thought about stack and keep adding as long as me is larger than top of stack while content of stack is larger me, keep popping.
    But what I stuck was in your example, when index is 3 with values [1,3,2,1], I thought I have to compute all possible rectangles such that [1]=1, [2,1]=2, [3,2,1]=3, [1,3,2,1]=4,
    but no videos explain why I don't have to compute the rectangle between two indices [0, 3] and instead they just compute [1, 3] which means we always guarantee that area between indices [1, 3] always larger than indices [0, 3].
    I don't understand how come area between [1, 3] always larger than [0, 3] ?

  • @user-sl5vw4vi6s
    @user-sl5vw4vi6s Před 5 měsíci

    It is a shame you don't make videos like these anymore. You are much more didactic than the tops G's on youtube on this topic.

  • @subham-raj
    @subham-raj Před 4 lety +3

    *We can do this with only single stack too*

  • @delmarfenn7068
    @delmarfenn7068 Před 7 lety

    Would the largest rectangle be in the empty space and not the "stacks"?

  • @thedrumify
    @thedrumify Před 7 lety

    I don't know JavaScript, but isn't there an error in the while condition?

  • @JackBauerDev
    @JackBauerDev Před 7 lety

    What is the complexity for this algo? This can be done in O(n) if you drop the stacks and only use a few variables using intelligent linear drag.

    • @someone6949
      @someone6949 Před 7 lety +1

      This algorithm is clearly O(n). You can only ever add something to the stack once and pop it off once. Stack operations are O(1), so linear on size of input histogram.

  • @TimothyLeeBanks
    @TimothyLeeBanks Před 6 lety

    man started the vid with "what up mothafuckas" LMFAO

  • @victorbizimis9484
    @victorbizimis9484 Před 7 lety

    how are you writting in reverse ?

  • @JFETBJT
    @JFETBJT Před 8 lety

    In the first example (8:16) you are computing size as 1*(5-0), where 5 is out of range of histogram positions. In your implementation pos is always < hist.length. So my question is how would you obtain maxSize == 5, for the first example of histogram [1,3,2,1,2]?

    • @jackson-gabbard
      @jackson-gabbard  Před 8 lety +1

      So, this algorithm has two loops. One loop, which I think is the one you've pointed out, only goes from 0 to 4 for this input. And you're right, that loop wouldn't pick up the 1x5 rectangle. Luckily, there's also a second loop. During this loop the position is actually 5, because the final incrementation has happened and pos is now equal to the length of the histogram array (that is, it's 5). So, in this second loop, you're actually using the full width of the histogram in the subtraction part of the formula.

  • @gokukakarot6323
    @gokukakarot6323 Před 4 lety

    Fuuuuuucccckkkk, this is mindblowing explanation. Please make more videos like this. Also normally I watch videos at 1.5x this is the first video I watched at 0.75x

  • @shankardaruga3264
    @shankardaruga3264 Před 6 lety

    The best explanation :)

  • @Anonymous-ql7gn
    @Anonymous-ql7gn Před 8 lety

    Simly Best tech video I ever seen.

  • @Lashovadjs
    @Lashovadjs Před 7 lety

    Really some clever tricks, interesting.

  • @giubueno
    @giubueno Před 7 lety

    Excellent video two thumbs up for it and one down for the code in Javascript because I think it would be more descriptive in Java.

  • @keepallprivate7616
    @keepallprivate7616 Před 7 lety

    I wonder if it will going to be really a rectangle at the end of the day.. a square maybe?

  • @ravinder090191
    @ravinder090191 Před 7 lety

    Colol explanation. Thanks. Please come up with a video on Dynamic Programming. Thanks.

  • @randomshotz13
    @randomshotz13 Před 7 lety

    I'd be very interested in seeing a solution with non uniform class widths I imagine a similar approach but where the total width passed through would be stored rather than the starting location. If given the question from the video in an interview. Would the interviewer prefer I simplify the problem and assume unity or that I handled for other cases?

  • @tienanh2007
    @tienanh2007 Před 7 lety

    How does the letters just slide off like that ?

  • @louisfaeth7003
    @louisfaeth7003 Před 7 lety

    Quick question, if a z axis was involved of the histogram, how would that look in code? Sorry I am uber new like just beginning codecademy new :

    • @ms-channel-4u
      @ms-channel-4u Před 7 lety

      that would just introduce an extra stack shit. and some more iteration development

    • @louisfaeth7003
      @louisfaeth7003 Před 7 lety

      Thank you, so would you then have to calculate cubic area to find stack values

  • @MrGowds
    @MrGowds Před 7 lety

    presentation is dope !

  • @tagadvance
    @tagadvance Před 7 lety

    What might this algorithm be used for? What value is there in knowing the area and position of the largest rectangle?

    • @JacksonGabbard
      @JacksonGabbard Před 7 lety +1

      TaG, there are a million real-world algorithms where this might be useful. For instance, image processing. If you're trying to identify the dominant luminosity range of an image perhaps. In audio processing, you might use a similar approach to determine the primary frequency range in an audio sample. You might also use it in GPS-related calculations, looking for the period of movement within a range of time.

  • @TomusMedia
    @TomusMedia Před 8 lety

    I don't understand this, how do you write so good backwards?

  • @baseballmike44
    @baseballmike44 Před 8 lety +2

    Hey, I was wondering if there is a specific reason you initialized maxlength to -Infinity instead of 0?

    • @salmanbehen4384
      @salmanbehen4384 Před 3 lety

      Both would work in this case, but it is a usual practice to do so.

  • @insights15243
    @insights15243 Před 5 lety

    Regarding your brute force method, if I got you right then I think you're wrong: take the histogram [9,8]. Your brute force method will return 9 while the right answer is 16. You need to go both right and left (and not only right)

  • @Adolf1Extra
    @Adolf1Extra Před 7 lety

    I know I'm late but shoulda mentioned function declaration hoisting so you could just put popthatshit after the for loop

  • @toomasvendelin
    @toomasvendelin Před 2 lety

    A bonus question: is the author/presenter left-handed or right handed? Many thanks for a stellar example on how to make a CZcams video!

  • @tintiniitk
    @tintiniitk Před 3 lety

    How has he created this visual? It looks like he's writing on a transparent glass and he's on the other side.. but then that'd mean he is writing in a mirrored manner. If he's writing on a mirror, then how is he behind the board?

  • @tracyg2158
    @tracyg2158 Před 8 lety +1

    I absolutely loved this! Really wonderful job explaining the problem and working out a solution!!

  • @asbearful
    @asbearful Před 7 lety

    Does your solution work with non continuous histogram like [0,3,2,3,0,4,7,3]?

    • @Drtsaga
      @Drtsaga Před 7 lety

      It does, why wouldn't it?

  • @brifog69
    @brifog69 Před 7 lety

    How the fuck did he write those words at the start in reverse so well?

  • @Copainbig
    @Copainbig Před 5 lety

    I need more of those videos! Fuck! This shit is fucking clear!

  • @ruffert100
    @ruffert100 Před 8 lety +3

    Great video performance!
    But from the algorithmic point of view I would suggested this (in pseudo code)
    maxArea = 0
    for all l:listOfConnectedRectangles in listOfListOfConnectedRectangles
    do
    currentArea = width(l) * min(height of rectangles in l)
    maxArea = max( maxArea, currentArea )
    end
    And ah well, yes, I would also need to specify how to derive listOfListOfConnectedRectangles. :)
    Anyway, this is a suggestion from the top of my hat, what do you think?

    • @skripnikalexander
      @skripnikalexander Před 8 lety

      In your code the min(height of rectangles in l) will give an incorrect result, as the best area of listOfConnectedRectangles is not the lowestHeight(l)*width(l). E.g. in case of l = [1, 2, 4, 5], the currentArea should 4 * 2 = 8 instead of 1 * 4 = 4

    • @ruffert100
      @ruffert100 Před 8 lety

      Need to think about that. Thanks :)

    • @itizir
      @itizir Před 7 lety

      Doesn't it depend on how Eduard defines 'listOfConnectedRectangles' and 'height of rectangles in l'?
      I think he rather meant something like (given your example input):
      "take the rectangle of width 4 (starting at 1); its height is 1 (the min value), so its area is 4;
      now take the next rectangle, of width 3; the min is now 2, so the size is 6; etc. etc."
      In this case it would be correct.
      The problem is it is very far from optimal: it is just the 'brute force' approach Jackson talks about at the beginning of the video (2:12). Since you potentially loop over all the columns for each and every column, it takes O(N^2), while the stack-based solution presented here is O(N)...

  • @joshuaduncan1477
    @joshuaduncan1477 Před 7 lety

    Wonderful content. subscribed

  • @AndrewReisdorph
    @AndrewReisdorph Před 8 lety +24

    Now that's a lot of shit popping

  • @kristopherrobinson9805

    Wow. Great video.

  • @kevincui1631
    @kevincui1631 Před 5 lety

    you don't need the weird sound effect. It messes things up