Largest Square of 1's in A Matrix (Dynamic Programming)

Поделиться
HTML-код
  • Опубликовано: 9 сен 2024
  • Check out the detailed data structures and algorithms course at www.interviewa...
    Dynamic Programming - A ridiculously simple explanation.
    In the video, I show you how we can turn a complex coding interview question into a simple one through dynamic programming.
    The problem is also known as 'Maximum Sub Square Matrix' - Given a matrix of 0s and 1s, find the biggest sub-square matrix entirely of 1s.
    Music: Modern Theme by Nicolai Heidlas

Комментарии • 159

  • @pascalfragnoud2846
    @pascalfragnoud2846 4 года назад +13

    You don't actually have to keep a record of the full matrix, the only line is enough.
    So you can make a 2 by n array, and use one line as your cache, and the other one for your computations.
    To select which is which: For index i == 3 for example, you'd access your computation line with (3 & 1), which gives you 1, and your cache is the other one, which you can access with ((i & 1) ^ 1) or in many other ways.
    This reduces space complexity down from n squared to 2*n, a huge improvement for very large matrices.

  • @davidjames1684
    @davidjames1684 3 года назад +1

    I would go about this differently... Since we know the input matrix is 4 rows and 5 columns, the largest square of 1s there can be is 4x4, so the only place that can be is at the upper left corner or 1 element to the right of that. As soon as we scan across the top row, we see a 0, and realize a 4x4 of 1s cannot be present. We repeat this logic with 3x3 and find it and then we are done. No need to fuss with squares of size 2x2 in this example because we are checking largest (4x4) to smallest (1x1) and stopping when we find one (in this case stopping at 3x3).
    More specifics about the algorithm at the 3x3 check step would be scan across until we find 3 ones in a row (literally), go back to that "home" position (the leftmost element), and scan down to see if there are 3 ones in a column. If so, now we have a 3x3 "outline" so check the remaining elements inside that (only 4 more elements to check). If all are ones, we are done.
    Actually an improvement of this algorithm can be to first count up the # of 1s. Since we only have 14, we know that a 4x4 square of 1s is not possible, so immediately start looking for 3x3s since there are at least 9 1s.
    There are likely many more algorithms that will solve this too. Probably dozens.

  • @shashanksingh99
    @shashanksingh99 6 лет назад +57

    Dude you are one of the best thing that happened to RUclips (For Programmers atleast :) )

  • @CompleteMeYT
    @CompleteMeYT 5 лет назад +1

    Good lesson. One small suggestion: we can avoid that whole if-else by simply doing cache[i][j] = (1 + min(...)) * matrix[i][j]. With that solution, we don't need to clone the entire matrix. We can start with an uninitialized matrix, copy the first row and first column, then iterate starting at 2nd row and 2nd column.

  • @analogylibrary
    @analogylibrary 6 лет назад +1

    Good one but different too. Actually the idea of explaining on board like you are being interviewed earned my subscription.

  • @paritoshpradeep4626
    @paritoshpradeep4626 4 года назад +1

    Bro I have started my journey towards DS & Algos for interview purpose just now and have solved many questions and have watched many videos by other people, but the way u explained is awesome ,keep it up and make more such videos for the community.

  • @jakelazareth1
    @jakelazareth1 4 года назад +1

    Perhaps the best explanation I've seen for this problem. Thank you!

  • @anojk1
    @anojk1 6 лет назад +6

    Thanks, Irfan. Remarkable work, every effort you put in this is appreciable.

  • @GurdeepSabarwal
    @GurdeepSabarwal 5 лет назад

    i was trying to understand this problem , and No one did explain this problem better than this guys(Iterative Approach). you are awesome IrFaN!

  • @dvdh8791
    @dvdh8791 5 лет назад +12

    Space complexity can be reduced to O(N) by only keeping track of the previous row and the current row of the cache.

    • @sarthaksrivastav3408
      @sarthaksrivastav3408 4 года назад

      Or it can be O(1) if you just modify the matrix given to you.

  • @TonyStark-lg7ux
    @TonyStark-lg7ux 5 лет назад +2

    for the first time i subscribed a channel before looking into number of subscribers.
    great work, u are an excellent in terms of teaching anything.

  • @yannicbrandstetter8265
    @yannicbrandstetter8265 5 лет назад +24

    pls give the interviewer a mic or put him closer to the cam

  • @owaiswasim8911
    @owaiswasim8911 4 года назад +1

    This is the best step by step approach i have found.. Thanx!!

  • @saplingqwason
    @saplingqwason 6 лет назад +1

    interesting solution. I would iterate through the matrix , adding to a temp until I see a zero-->Only run a nested loop if temp> current largest. --> Nested loop will continue until a zero or confirmation of replacing maximum. This would allow me to stop the loop "early" by comparing remaining idx positions e.g. min(endofx-currentx ,endofy-currenty) < result---> return result
    Another interesting way could be to sum each array and calculate maximum results backwards until you finally find one equal to its maximum square or the maximum possible == result

  • @kant.shashi
    @kant.shashi 3 года назад

    perfect way to approach a DP problem

  • @TigraStyle
    @TigraStyle 3 года назад +1

    awesome explanation, thanks for this!

  • @ajaikumar958
    @ajaikumar958 4 года назад

    Irfan, keep posting more great videos like this. These are so valuable for many people wanting to get the thought process for solving any question.

  • @angelv.g.8046
    @angelv.g.8046 4 года назад +20

    This algorithm can be improved off if you start indexes as follow i=1 , j=1, since the first row and first column never changed.

    • @isingcauseimliving
      @isingcauseimliving 4 года назад

      I used the same technique in my Computation Fluid Dynamics class...

  • @chiraggupta1557
    @chiraggupta1557 4 года назад +3

    you are a great teacher..i understood it thoroughly! thanks a lot & keep posting :)

  • @kambalavijay6800
    @kambalavijay6800 4 года назад

    Irfan bhai solution itna simple kaise ho sakta? What great a way to start and take this down to solution very much appreciable work Irfan bhai.

  • @MrThepratik
    @MrThepratik 5 лет назад +1

    Nice one Irfan
    Have been looking for different approaches for dynamic programming . This really helps a lot !!

  • @janesmith8561
    @janesmith8561 6 лет назад +12

    This video was so helpful thank you! In the future could you please go over how you came up with a solution instead of just jumping into it? Also I was SHOOK when you looked directly into the camera for the first time during the interview.

    • @IrfanBaqui
      @IrfanBaqui  6 лет назад +1

      Jane Smith Haha, I should look into the camera more in that case 😆
      And I'm glad you found it useful. I'll look into explaining my thought process even more, thanks for the feedback.

  • @arunkumarm6004
    @arunkumarm6004 2 года назад

    I need answer for this question
    Given an array of Given an array of N integers where each number a[x] indicates a stack of cubical bricks of height a[x]
    Essentially the array represents N stacks of bricks. The goal is to determine the largest nxn matrix (square matrix ) embedded in this array of stack
    Input format:
    First line indicates the size of the integer array say N
    Each of the next N lines represent the height of the stack at index x where 12,+x

  • @fatcatgaming695
    @fatcatgaming695 5 лет назад

    Absolutely love these, the time is spend going over and explaining the problem / solution is invaluable. Thank you.

  • @AyushRaj-gf2ce
    @AyushRaj-gf2ce 4 года назад

    could understand the logic while the video of tushar roy...and you made me understand it so easily..great explanation! subscribed and looking for more questions on graph and dynamic programming

  • @crothert
    @crothert 6 лет назад +5

    ty for helping me prep for interview

  • @Shini1984
    @Shini1984 4 года назад

    Going bottom right corner does not differ at all from top left. You can just "flip the board", meaning you can start from bottom right corner instead (I think this is what is called "bottom up solution" when you start from the end of your computational area). Same as starting with top left, when starting from bottom right you can skip bottom row and right column as they will never have a value bigger than 1.
    This is how I solved it when I first encountered this question on leetcode.

  • @niharikaepuri3305
    @niharikaepuri3305 6 лет назад +2

    Sir, your videos are really helpful. Please upload videos like this more often.

  • @7810
    @7810 5 лет назад

    The solution is so graceful and well explanatory! Many thanks for the lesson.

  • @zionsiton3690
    @zionsiton3690 2 года назад

    Great video and approach to answering the question for a coding interview by the way.
    One thing I would change based on your solution would be to start the iterators at 1 instead of zero. Not only would that save iterations (as you don't need to change the cloned values when i or j are zero, but it also removes the need to check if i or j are zero.
    Again, great video

  • @fredschneider7475
    @fredschneider7475 4 года назад

    Nice elegant explanation, Irfan!

  • @pranavkumarsoni7518
    @pranavkumarsoni7518 2 года назад

    very great explanation.

  • @addtextapp
    @addtextapp 5 лет назад

    Really great explanation, thank you. One important case: when matrix has only 1 row/column the result must be assigned to 1 if there's at least one occurrence of 1.

  • @eduardopetry911
    @eduardopetry911 6 лет назад +6

    Thank you for accepting the feedback! Great video, the problem presented is solved in a very interesting way.
    I'd like to contribute with subtitles, can you enable acceptance of contributions from viewers?

    • @IrfanBaqui
      @IrfanBaqui  6 лет назад +2

      That would be amazing! I just enabled accepting contributions. Looking forward to seeing yours.

  • @wibbthebubblyt5174
    @wibbthebubblyt5174 5 лет назад +16

    "mhm"

  • @arupnaskar3818
    @arupnaskar3818 6 лет назад +3

    very smart and good logic sir.....

  • @akshaysolanki5164
    @akshaysolanki5164 3 года назад

    awesome explanation

  • @johnsonhan2000
    @johnsonhan2000 6 лет назад +2

    You are so underrated.

  • @satishshingade8514
    @satishshingade8514 3 года назад

    very nice explanation thank you

  • @sakshamchhimwal322
    @sakshamchhimwal322 17 дней назад

    Clear Concise Awesome!!!!

  • @rohit236c
    @rohit236c 4 года назад +1

    really great video man!

  • @SaurabhNarhe
    @SaurabhNarhe 6 лет назад

    You are doing really great. Helping me learn so much. Thank You!

  • @prateeksaxena7808
    @prateeksaxena7808 4 года назад

    Please post more video lectures for coding questions.

  • @serhiypidkuyko4206
    @serhiypidkuyko4206 6 лет назад +3

    Hi, Irfan.
    Thank you for your video-task and its very smart solution.
    But:
    1. that solution isn't good (not optimal) when the matrix has only a few zeros. For example if matrix has no zeros the solution could be found much more faster (the corresponding solution based on calculation the maximum square with up-left value=1)
    2. you don't need to create one more matrix - just one-dimensional array (one line or one column of the given matrix) will be fine. So if your initial (given) matrix is m times n and m

  • @joejeetha
    @joejeetha 5 лет назад +2

    I don't think we should do an array clone. all the value transfers can be in the one nested loop.

  • @vaibhavshukla2658
    @vaibhavshukla2658 4 года назад

    Great Explanation Irfan

  • @yuanyuanliu7439
    @yuanyuanliu7439 3 года назад

    very clear! great explaination!

  • @safiyapathan7510
    @safiyapathan7510 6 лет назад +1

    B: Tips to ace your coding interviews
    It would be very helpful!

  • @pinaksawhney4941
    @pinaksawhney4941 4 года назад

    Thank you so much. keep doing videos like these!

  • @apratimtiwari5555
    @apratimtiwari5555 4 года назад

    Amazing explanation!

  • @SudhanshuSrivastavaIndia
    @SudhanshuSrivastavaIndia 5 лет назад

    Fab Irfan... you made it easy man.. Thanks

  • @sarthaksrivastav3408
    @sarthaksrivastav3408 4 года назад

    Great explanation, thank you.

  • @titouant1936
    @titouant1936 6 лет назад +17

    just begin your 2 for loops at i=1 and j=1 so you don't have to test for them to be zero.

    • @arturo9790
      @arturo9790 5 лет назад +6

      However if the entire matrix is composed of 0s except for a 1 at index 0,1 , then starting at i=1 and j=1 will never look at this element, and would output that the largest square is 0. However it should actually be 1.

    • @arafathossain4794
      @arafathossain4794 4 года назад

      This comment holds more value than the actual video

  • @chikinfrydsteak
    @chikinfrydsteak 3 года назад

    Very helpful! Thanks so much

  • @vatsalanarang
    @vatsalanarang 4 года назад

    Your videos are great and the explanation is helpful, could you make more videos on interview questions.

  • @omgtruth171
    @omgtruth171 5 лет назад

    Dude you are the best teacher in DP I have ever seen! Could you do another DP problem: minimum score of polygon triangulation?

    • @rjose705
      @rjose705 4 года назад

      If you're given an array for the polygon's, sort the array and return the numbers from indexes 0 to n-2 where n is the length.

  • @BrentSnider
    @BrentSnider 3 года назад

    Great video

  • @AshishShukla-ro8oy
    @AshishShukla-ro8oy 5 лет назад +2

    what if we have to find max size of rectangle that can be formed....any idea???

  • @laventin4332
    @laventin4332 4 года назад

    very elegant

  • @sojuthomas7727
    @sojuthomas7727 6 лет назад +5

    very difficult problem. but I understand your explanation s.

  • @sarcastitva
    @sarcastitva 5 лет назад

    Smooth as butter.

  • @uneq9589
    @uneq9589 5 лет назад

    The implementation was quite easy!

  • @just4uchin
    @just4uchin 6 лет назад +2

    Amazing!

  • @wucas123
    @wucas123 5 лет назад

    Well done!

  • @ditikrushnagiri5622
    @ditikrushnagiri5622 5 лет назад

    Thanks , Irfan .

  • @itarukishikawa6845
    @itarukishikawa6845 5 лет назад

    def largestMatrix(arr):
    size = len(arr)
    result = 0
    arr2 = arr.copy()
    for row in range(1, size):
    for col in range(1, size):
    if arr[row][col] == 1:
    arr2[row][col] = min(arr2[row-1][col-1], arr2[row-1][col], arr2[row][col-1]) + 1
    result = max(result, arr2[row][col])
    return result
    With less code in Python

  • @joydas1685
    @joydas1685 6 лет назад

    Simple and clear explanation
    Keep on bringing more coding problems like this..

  • @rongrongmiao4638
    @rongrongmiao4638 6 лет назад +2

    You should return result * result for the area. Currently you have the maximum length of the square. : )

    • @vrezhgulyan6834
      @vrezhgulyan6834 6 лет назад +2

      Rongrong Miao He is returning the min of the neighbors + 1. The question asks for the largest square, which is the length of the height or width which are equal. The question doesn’t ask for the area.

  • @jeff4615
    @jeff4615 4 года назад

    Nice video

  • @kambalavijay6800
    @kambalavijay6800 4 года назад

    Since we don't do anything when i=0 or j=0 why don't we start from i=1 and j=1? Just asking

  • @MickaelBonfill
    @MickaelBonfill 5 лет назад +1

    This is nice but I thought you will present a solution to get the largest square (I mean it's coordinates in the given space or matrix). I think to get the coordinates it shouldn't be harder, maybe cache the indexes i and j when you pass in your (currentResult > result) statement ?
    I don't know if it's better than an algorithm using a voronoi diagram where each voronoi vertex is a 0 from the matrix, then use something like the Largest Empty Circle but for Square to find the coordinates. I think for big matrices this is something to benchmark.

    • @jigaurafael6974
      @jigaurafael6974 3 года назад

      You have the result, thats 3. Just search it in the cache matrix, memorate the row and the column of the result, in this case its (4,4). Then you extract 3 and you have the start of the square matrix inside, and ofcourse number of rows and columns will be the same as the result, 3.

    • @jigaurafael6974
      @jigaurafael6974 3 года назад

      Pretty much the same that you said

  • @xenky0
    @xenky0 3 года назад

    Thank you
    Can you explain why can you lead to conclusion that:
    M(i,j)=min(of neighbors) + value(i,j)
    I cannot understand the reason.
    Thanks.

  • @huyvole9724
    @huyvole9724 5 лет назад

    Thanks. More video plz.

  • @jugsma6676
    @jugsma6676 5 лет назад

    WOW, That was so nice.

  • @PowKu10
    @PowKu10 6 лет назад +1

    LeetCode 221, nice solution!

  • @ujurak3899
    @ujurak3899 4 года назад

    Is a cache really necessary here? It seems modifying the matrix in place has no deficit to performance.

  • @chinmayanand896
    @chinmayanand896 6 лет назад

    good work brother....

  • @jamsrandorjbatbayar3652
    @jamsrandorjbatbayar3652 4 года назад

    Thank you very much!

  • @sid007ashish
    @sid007ashish 4 года назад

    Can someone clear my doubt?
    Why is this one dynamic programming? Is it because of the cache(memoization)?

  • @Steve-ft8ux
    @Steve-ft8ux 4 года назад

    well explain, thank you

  • @nikhilb3880
    @nikhilb3880 5 лет назад +1

    Interviewer will be like, "why are you explaining me the problem?"

  • @axeliuxTEC
    @axeliuxTEC 4 года назад

    Do you need the cache at all ? Looks like we could just override the array. Obviously in real application you might just need to find the area without messing around with it by overriding it .

  • @chenyangwang7232
    @chenyangwang7232 4 года назад

    A posted solution is good of course. The thing is how to come up with this solution. What if we didn't see this or a similar question before during the interview?

  • @TM-qc5oz
    @TM-qc5oz 5 лет назад

    What is the intuition behind considering a 1 to be in bottom right instead of top left, for the iterative solution ?

  • @Xellos976
    @Xellos976 6 лет назад

    Great videos! Can you increase the volume of the interviewer next time?

  • @alisheheryar1770
    @alisheheryar1770 2 года назад

    Sometimes I got zoned out. Nice effort but still room for improvement.

  • @omartahboub2900
    @omartahboub2900 5 лет назад

    WOW !! Quite impressive :) !!!

  • @lokeshwaran5650
    @lokeshwaran5650 5 лет назад

    Best way of watching

  • @iarjun1773
    @iarjun1773 4 года назад

    Your explanation is nice I really like it. However, I just want to know why you adopted this approach, like iterating through the neighbors. We already have a matrix and it consists a sub matrix of 1's. Can we go with any other approach? Is there any algorithm to find sub matrix in such a case. I will be very much thankful if I get an answer, since I have seen lots of example with the same approach as yours, however, unable to get the reason for doing so. Implementation was really easy anyways.

  • @nspranav
    @nspranav 6 лет назад

    Thank you. can you also show the recursive way of doing this.

  • @chloekimball536
    @chloekimball536 5 лет назад

    How can this method be extend to find submatrix with the largest sum? (now matrix has both negative and non negative values)

  • @researchandbuild1751
    @researchandbuild1751 6 лет назад

    Ive been watching a lot of these interview videos and it seems like so many of them are the similar type of problems always needing recursion "largest item" type of problems

  • @kid_kulafu_1727
    @kid_kulafu_1727 5 лет назад

    Hello. How is this optimal when your using inner loop. Run time O(n**2) even though you cache it. I will work for every J right? Sorry im so noob. Thanks.

  • @lamusiquerie1871
    @lamusiquerie1871 4 года назад +3

    Epitech Rennes rpz

  • @shivajunna
    @shivajunna 5 лет назад +1

    I have one simple question! How do you come up with the instantaneous solution??? How is it possible? What needs to be done to be at that position?

    • @john_rambo_27098
      @john_rambo_27098 4 года назад

      :)

    • @xenky0
      @xenky0 3 года назад

      Yeah I did not understand the process of finding the optimal structure for this problem, can anyone explain to me?

  • @naveenn7935
    @naveenn7935 6 лет назад

    thank you!

  • @chuckywang
    @chuckywang 5 лет назад

    How did you come up with the intuition to form this solution?

  • @cwagnello
    @cwagnello 6 лет назад

    You need to return the max size of the square. Right?

  • @idobenamram3743
    @idobenamram3743 6 лет назад

    so good.

  • @just4uchin
    @just4uchin 6 лет назад

    Please make one on 0/1 Knapsack problem