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.
@davidjames16843 жыл бұрын
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.
@CompleteMeYT5 жыл бұрын
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.
@saplingqwason6 жыл бұрын
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
@yannicbrandstetter82655 жыл бұрын
pls give the interviewer a mic or put him closer to the cam
@dvdh87915 жыл бұрын
Space complexity can be reduced to O(N) by only keeping track of the previous row and the current row of the cache.
@sarthaksrivastav34084 жыл бұрын
Or it can be O(1) if you just modify the matrix given to you.
@paritoshpradeep46264 жыл бұрын
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.
@GurdeepSabarwal5 жыл бұрын
i was trying to understand this problem , and No one did explain this problem better than this guys(Iterative Approach). you are awesome IrFaN!
@analogylibrary6 жыл бұрын
Good one but different too. Actually the idea of explaining on board like you are being interviewed earned my subscription.
@Shini19844 жыл бұрын
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.
@kant.shashi4 жыл бұрын
perfect way to approach a DP problem
@kambalavijay68004 жыл бұрын
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.
@jakelazareth14 жыл бұрын
Perhaps the best explanation I've seen for this problem. Thank you!
@angelv.g.80465 жыл бұрын
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.
@isingcauseimliving4 жыл бұрын
I used the same technique in my Computation Fluid Dynamics class...
@wibbthebubblyt51745 жыл бұрын
"mhm"
@owaiswasim89114 жыл бұрын
This is the best step by step approach i have found.. Thanx!!
@ajaikumar9584 жыл бұрын
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.
@zionsiton36902 жыл бұрын
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
@shashanksingh996 жыл бұрын
Dude you are one of the best thing that happened to KZbin (For Programmers atleast :) )
@joejeetha6 жыл бұрын
I don't think we should do an array clone. all the value transfers can be in the one nested loop.
@anojk16 жыл бұрын
Thanks, Irfan. Remarkable work, every effort you put in this is appreciable.
@AyushRaj-gf2ce5 жыл бұрын
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
@fatcatgaming6955 жыл бұрын
Absolutely love these, the time is spend going over and explaining the problem / solution is invaluable. Thank you.
@prateeksaxena78084 жыл бұрын
Please post more video lectures for coding questions.
@TonyStark-lg7ux5 жыл бұрын
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.
@addtextapp5 жыл бұрын
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.
@titouant19366 жыл бұрын
just begin your 2 for loops at i=1 and j=1 so you don't have to test for them to be zero.
@arturo97906 жыл бұрын
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.
@arafathossain47945 жыл бұрын
This comment holds more value than the actual video
@janesmith85616 жыл бұрын
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.
@IrfanBaqui6 жыл бұрын
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.
@TigraStyle3 жыл бұрын
awesome explanation, thanks for this!
@78106 жыл бұрын
The solution is so graceful and well explanatory! Many thanks for the lesson.
@serhiypidkuyko42066 жыл бұрын
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
@crothert6 жыл бұрын
ty for helping me prep for interview
@eduardopetry9116 жыл бұрын
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?
@IrfanBaqui6 жыл бұрын
That would be amazing! I just enabled accepting contributions. Looking forward to seeing yours.
@MrThepratik5 жыл бұрын
Nice one Irfan Have been looking for different approaches for dynamic programming . This really helps a lot !!
@niharikaepuri33056 жыл бұрын
Sir, your videos are really helpful. Please upload videos like this more often.
@fredschneider74754 жыл бұрын
Nice elegant explanation, Irfan!
@chiraggupta15575 жыл бұрын
you are a great teacher..i understood it thoroughly! thanks a lot & keep posting :)
@chenyangwang72324 жыл бұрын
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?
@vatsalanarang4 жыл бұрын
Your videos are great and the explanation is helpful, could you make more videos on interview questions.
@Ashish.Shukla95 жыл бұрын
what if we have to find max size of rectangle that can be formed....any idea???
@rongrongmiao46386 жыл бұрын
You should return result * result for the area. Currently you have the maximum length of the square. : )
@vrezhgulyan68346 жыл бұрын
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.
@itarukishikawa68455 жыл бұрын
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
@axeliuxTEC5 жыл бұрын
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 .
@safiyapathan75106 жыл бұрын
B: Tips to ace your coding interviews It would be very helpful!
@omgtruth1715 жыл бұрын
Dude you are the best teacher in DP I have ever seen! Could you do another DP problem: minimum score of polygon triangulation?
@RohanDaDev5 жыл бұрын
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.
@vaibhavshukla26584 жыл бұрын
Great Explanation Irfan
@pranavkumarsoni75183 жыл бұрын
very great explanation.
@TM-qc5oz5 жыл бұрын
What is the intuition behind considering a 1 to be in bottom right instead of top left, for the iterative solution ?
@SaurabhNarhe6 жыл бұрын
You are doing really great. Helping me learn so much. Thank You!
@xenky04 жыл бұрын
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.
@sojuthomas77276 жыл бұрын
very difficult problem. but I understand your explanation s.
@MickaelBonfill5 жыл бұрын
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.
@jigaurafael69743 жыл бұрын
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.
@jigaurafael69743 жыл бұрын
Pretty much the same that you said
@sid007ashish4 жыл бұрын
Can someone clear my doubt? Why is this one dynamic programming? Is it because of the cache(memoization)?
@ujurak38994 жыл бұрын
Is a cache really necessary here? It seems modifying the matrix in place has no deficit to performance.
@pinaksawhney49414 жыл бұрын
Thank you so much. keep doing videos like these!
@kambalavijay68004 жыл бұрын
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
@apratimtiwari55554 жыл бұрын
Amazing explanation!
@yuanyuanliu74394 жыл бұрын
very clear! great explaination!
@rohit236c5 жыл бұрын
really great video man!
@arupnaskar38186 жыл бұрын
very smart and good logic sir.....
@johnsonhan20006 жыл бұрын
You are so underrated.
@SudhanshuSrivastavaIndia5 жыл бұрын
Fab Irfan... you made it easy man.. Thanks
@satishshingade85144 жыл бұрын
very nice explanation thank you
@uneq95895 жыл бұрын
The implementation was quite easy!
@iarjun17735 жыл бұрын
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.
@shivajunna5 жыл бұрын
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_270985 жыл бұрын
:)
@xenky04 жыл бұрын
Yeah I did not understand the process of finding the optimal structure for this problem, can anyone explain to me?
@myhomeariboyina96064 жыл бұрын
A, B and C in same order you have given
@chikinfrydsteak3 жыл бұрын
Very helpful! Thanks so much
@chloekimball5366 жыл бұрын
How can this method be extend to find submatrix with the largest sum? (now matrix has both negative and non negative values)
@ditikrushnagiri56225 жыл бұрын
Thanks , Irfan .
@laventin43324 жыл бұрын
very elegant
@sinhamohit6 жыл бұрын
Great explanation. Thank you.
@researchandbuild17516 жыл бұрын
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
@just4uchin6 жыл бұрын
Please make one on 0/1 Knapsack problem
@sarcastitva5 жыл бұрын
Smooth as butter.
@alisheheryar17703 жыл бұрын
Sometimes I got zoned out. Nice effort but still room for improvement.
@joydas16856 жыл бұрын
Simple and clear explanation Keep on bringing more coding problems like this..
@chuckywang5 жыл бұрын
How did you come up with the intuition to form this solution?
@cwagnello6 жыл бұрын
You need to return the max size of the square. Right?
@nspranav6 жыл бұрын
Thank you. can you also show the recursive way of doing this.
@sakshamchhimwal3223 ай бұрын
Clear Concise Awesome!!!!
@kid_kulafu_17276 жыл бұрын
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.
@huyvole97246 жыл бұрын
Thanks. More video plz.
@harshhundiwala46216 жыл бұрын
Awesome explanation
@Xellos9766 жыл бұрын
Great videos! Can you increase the volume of the interviewer next time?
@PowKu106 жыл бұрын
LeetCode 221, nice solution!
@walterwhite64995 жыл бұрын
So, when you start at i = j = 0, won't i-1,j would give an out of bounds error?
@watcher_1095 жыл бұрын
Its explicitly checked for i=0 & j=0 and the same value as the matrix is copied to the dp array.
@nikhilb38805 жыл бұрын
Interviewer will be like, "why are you explaining me the problem?"
@BrentSnider3 жыл бұрын
Great video
@jugsma66765 жыл бұрын
WOW, That was so nice.
@chinmayanand8966 жыл бұрын
good work brother....
@jamsrandorjbatbayar36525 жыл бұрын
Thank you very much!
@wucas1235 жыл бұрын
Well done!
@lokeshwaran56505 жыл бұрын
Best way of watching
@Steve-ft8ux4 жыл бұрын
well explain, thank you
@shiriusmt6 жыл бұрын
I think instead of cache[i][j] = 1 + min(...); it should be cache[i][j] = matrix[i][j] + min(...); right?
@jaivasani37736 жыл бұрын
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.
@vartikasharma25985 жыл бұрын
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
@xenky04 жыл бұрын
I dont understand why min() ??? Can anyone explain it?
@yashmehta71966 жыл бұрын
Did he really have to wear white
@ajaypilaniya85626 жыл бұрын
What if we need to find largest rectangle?
@yoyonel18086 жыл бұрын
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")