Тёмный

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

Irfan Baqui
Подписаться 32 тыс.
Просмотров 142 тыс.
50% 1

Check out the detailed data structures and algorithms course at www.interviewaccelerator.com
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

Наука

Опубликовано:

 

17 янв 2018

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 158   
@anojk1
@anojk1 6 лет назад
Thanks, Irfan. Remarkable work, every effort you put in this is appreciable.
@TonyStark-lg7ux
@TonyStark-lg7ux 5 лет назад
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.
@pascalfragnoud2846
@pascalfragnoud2846 4 года назад
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.
@fatcatgaming695
@fatcatgaming695 5 лет назад
Absolutely love these, the time is spend going over and explaining the problem / solution is invaluable. Thank you.
@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.
@MrThepratik
@MrThepratik 5 лет назад
Nice one Irfan Have been looking for different approaches for dynamic programming . This really helps a lot !!
@jakelazareth1
@jakelazareth1 4 года назад
Perhaps the best explanation I've seen for this problem. Thank you!
@paritoshpradeep4626
@paritoshpradeep4626 4 года назад
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.
@davidjames1684
@davidjames1684 3 года назад
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.
@chiraggupta1557
@chiraggupta1557 4 года назад
you are a great teacher..i understood it thoroughly! thanks a lot & keep posting :)
@niharikaepuri3305
@niharikaepuri3305 6 лет назад
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.
@owaiswasim8911
@owaiswasim8911 4 года назад
This is the best step by step approach i have found.. Thanx!!
@analogylibrary
@analogylibrary 5 лет назад
Good one but different too. Actually the idea of explaining on board like you are being interviewed earned my subscription.
@crothert
@crothert 6 лет назад
ty for helping me prep for interview
@dvdh8791
@dvdh8791 5 лет назад
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.
@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!
@SaurabhNarhe
@SaurabhNarhe 5 лет назад
You are doing really great. Helping me learn so much. Thank You!
@addtextapp
@addtextapp 4 года назад
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.
@pinaksawhney4941
@pinaksawhney4941 4 года назад
Thank you so much. keep doing videos like these!
@nspranav
@nspranav 6 лет назад
Thank you. can you also show the recursive way of doing this.
@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
@AshishShukla-ro8oy
@AshishShukla-ro8oy 5 лет назад
what if we have to find max size of rectangle that can be formed....any idea???
@sinhamohit
@sinhamohit 5 лет назад
Great explanation. Thank you.
@angelv.g.8046
@angelv.g.8046 4 года назад
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...
@yannicbrandstetter8265
@yannicbrandstetter8265 5 лет назад
pls give the interviewer a mic or put him closer to the cam
@TigraStyle
@TigraStyle 3 года назад
awesome explanation, thanks for this!
@arupnaskar3818
@arupnaskar3818 6 лет назад
very smart and good logic sir.....
@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
@rohit236c
@rohit236c 4 года назад
really great video man!
@fredschneider7475
@fredschneider7475 4 года назад
Nice elegant explanation, Irfan!
@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
@MickaelBonfill
@MickaelBonfill 5 лет назад
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
@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 ?
@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)
@safiyapathan7510
@safiyapathan7510 6 лет назад
B: Tips to ace your coding interviews It would be very helpful!
@janesmith8561
@janesmith8561 6 лет назад
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 лет назад
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.
@vatsalanarang
@vatsalanarang 4 года назад
Your videos are great and the explanation is helpful, could you make more videos on interview questions.
@harshhundiwala4621
@harshhundiwala4621 6 лет назад
Awesome explanation
@chuckywang
@chuckywang 5 лет назад
How did you come up with the intuition to form this solution?
@SudhanshuSrivastavaIndia
@SudhanshuSrivastavaIndia 5 лет назад
Fab Irfan... you made it easy man.. Thanks
@prateeksaxena7808
@prateeksaxena7808 4 года назад
Please post more video lectures for coding questions.
@cwagnello
@cwagnello 6 лет назад
You need to return the max size of the square. Right?
@saplingqwason
@saplingqwason 5 лет назад
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
@vaibhavshukla2658
@vaibhavshukla2658 4 года назад
Great Explanation Irfan
@CompleteMeYT
@CompleteMeYT 4 года назад
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.
@apratimtiwari5555
@apratimtiwari5555 3 года назад
Amazing explanation!
@yuanyuanliu7439
@yuanyuanliu7439 3 года назад
very clear! great explaination!
@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.
@eduardopetry911
@eduardopetry911 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 лет назад
That would be amazing! I just enabled accepting contributions. Looking forward to seeing yours.
@joejeetha
@joejeetha 5 лет назад
I don't think we should do an array clone. all the value transfers can be in the one nested loop.
@pranavkumarsoni7518
@pranavkumarsoni7518 2 года назад
very great explanation.
@huyvole9724
@huyvole9724 5 лет назад
Thanks. More video plz.
@satishshingade8514
@satishshingade8514 3 года назад
very nice explanation thank you
@shashanksingh99
@shashanksingh99 6 лет назад
Dude you are one of the best thing that happened to RU-vid (For Programmers atleast :) )
@chikinfrydsteak
@chikinfrydsteak 3 года назад
Very helpful! Thanks so much
@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.
@just4uchin
@just4uchin 6 лет назад
Please make one on 0/1 Knapsack problem
@akshaysolanki5164
@akshaysolanki5164 3 года назад
awesome explanation
@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.
@tusharchauhan2019
@tusharchauhan2019 6 лет назад
How did u come with logic??
@jugsma6676
@jugsma6676 5 лет назад
WOW, That was so nice.
@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?
@wibbthebubblyt5174
@wibbthebubblyt5174 5 лет назад
"mhm"
@johnsonhan2000
@johnsonhan2000 6 лет назад
You are so underrated.
@kant.shashi
@kant.shashi 3 года назад
perfect way to approach a DP problem
@sid007ashish
@sid007ashish 3 года назад
Can someone clear my doubt? Why is this one dynamic programming? Is it because of the cache(memoization)?
@uneq9589
@uneq9589 5 лет назад
The implementation was quite easy!
@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.
@sojuthomas7727
@sojuthomas7727 6 лет назад
very difficult problem. but I understand your explanation s.
@chinmayanand896
@chinmayanand896 6 лет назад
good work brother....
@wucas123
@wucas123 4 года назад
Well done!
@titouant1936
@titouant1936 6 лет назад
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 лет назад
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
@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.
@just4uchin
@just4uchin 6 лет назад
Amazing!
@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.
@jamsrandorjbatbayar3652
@jamsrandorjbatbayar3652 4 года назад
Thank you very much!
@Xellos976
@Xellos976 6 лет назад
Great videos! Can you increase the volume of the interviewer next time?
@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
@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
@Steve-ft8ux
@Steve-ft8ux 4 года назад
well explain, thank you
@sarcastitva
@sarcastitva 5 лет назад
Smooth as butter.
@ditikrushnagiri5622
@ditikrushnagiri5622 5 лет назад
Thanks , Irfan .
@ujurak3899
@ujurak3899 4 года назад
Is a cache really necessary here? It seems modifying the matrix in place has no deficit to performance.
@BrentSnider
@BrentSnider 3 года назад
Great video
@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 .
@shivajunna
@shivajunna 4 года назад
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?
@walterwhite6499
@walterwhite6499 5 лет назад
So, when you start at i = j = 0, won't i-1,j would give an out of bounds error?
@kunalfarmah43
@kunalfarmah43 5 лет назад
Its explicitly checked for i=0 & j=0 and the same value as the matrix is copied to the dp array.
@laventin4332
@laventin4332 4 года назад
very elegant
@omartahboub2900
@omartahboub2900 4 года назад
WOW !! Quite impressive :) !!!
@naveenn7935
@naveenn7935 6 лет назад
thank you!
@serhiypidkuyko4206
@serhiypidkuyko4206 6 лет назад
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
@jeff4615
@jeff4615 4 года назад
Nice video
@ajaypilaniya8562
@ajaypilaniya8562 6 лет назад
What if we need to find largest rectangle?
@yoyonel1808
@yoyonel1808 6 лет назад
For area of the largest rectangle (in submatrix of 1s), you have to use the solution to find the max rectangle in histogram and some Dynamic Programming logics. It's not hard to solve when you have the solution for the problem: "Largest rectangle in an Histogram")
@rajveersingh2056
@rajveersingh2056 6 лет назад
Awsome bro
@shiriusmt
@shiriusmt 5 лет назад
I think instead of cache[i][j] = 1 + min(...); it should be cache[i][j] = matrix[i][j] + min(...); right?
@jaivasani3773
@jaivasani3773 5 лет назад
Either of them would work. He is using 1 because he already knows that the value for matrix[i][j] is 1. See the condition else if (matrix[i][j] > 0). This means that the value is not zero, that means the value will be 1. Hope this helps.
@vartikasharma2598
@vartikasharma2598 5 лет назад
Yes, matrix[i][j] is probably a better generic answer if you are looking for a generic solution like longest increasing subsequence.. but for this question matrix[i][j] =1
@xenky0
@xenky0 3 года назад
I dont understand why min() ??? Can anyone explain it?
@joydas1685
@joydas1685 6 лет назад
Simple and clear explanation Keep on bringing more coding problems like this..
@idobenamram3743
@idobenamram3743 6 лет назад
so good.
@lokeshwaran5650
@lokeshwaran5650 5 лет назад
Best way of watching
@rongrongmiao4638
@rongrongmiao4638 6 лет назад
You should return result * result for the area. Currently you have the maximum length of the square. : )
@vrezhgulyan6834
@vrezhgulyan6834 6 лет назад
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.
Далее
Получилось у Миланы?😂
00:13
Просмотров 1,6 млн
Most Common Concepts for Coding Interviews
6:08
Просмотров 291 тыс.
Maximum Subsquare With Sides as X
10:48
Просмотров 37 тыс.
Google Coding Interview With A Competitive Programmer
54:17
Maximum Size Rectangle of All 1's Dynamic Programming
6:55
Это Xiaomi Su7 Max 🤯 #xiaomi #su7max
1:01
Просмотров 2 млн
ОБСЛУЖИЛИ САМЫЙ ГРЯЗНЫЙ ПК
1:00