Rotate Image - Matrix - Leetcode 48

Ғылым және технология

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Twitter: / neetcode1
Discord: / discord
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
Problem Link: neetcode.io/problems/rotate-m...
0:00 - Read the problem
3:25 - Drawing explanation
9:55 - Coding explanation
leetcode 48
This question was identified as a microsoft interview question from here: github.com/xizhengszhang/Leet...
#microsoft #matrix #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 284

  • @NeetCode
    @NeetCode2 жыл бұрын

    🚀 neetcode.io/ - A better way to prepare for Coding Interviews

  • @srinadhp
    @srinadhp2 жыл бұрын

    This has been one of the toughest problems for me. Very hard to visualize and always used to make mistakes even after multiple attempts. The way that you explained the approach is THE BEST. You made it so crystal clear in visualizing the solution. Thank you so much!

  • @sidkapoor9085

    @sidkapoor9085

    2 жыл бұрын

    I found it way easier, almost trivial when I stopped looking at the "2D matrix" and just at the input and output lists.

  • @caniaccombo123

    @caniaccombo123

    2 жыл бұрын

    @@sidkapoor9085 mind blown

  • @markomekjavic

    @markomekjavic

    2 жыл бұрын

    I honestly think this is a Hard problem when it comes to implementation.. you can see the idea but coming up with the double pointer approach and a loop, thats a different story!

  • @huansir1922

    @huansir1922

    Жыл бұрын

    @@markomekjavic yes,coming up with the double pointer approach , it seems hard

  • @princeanthony8525

    @princeanthony8525

    Жыл бұрын

    Same here.

  • @meowmaple
    @meowmaple2 жыл бұрын

    This is a clear explanation, but definitely still not the simplest. For me, the most straightforward method is to transpose the matrix and reverse each row. The code is simple and short. #transpose for row in range(len(matrix)): for col in range(row,len(matrix)): temp = matrix[row][col] matrix[row][col] = matrix[col][row] matrix[col][row] = temp #reverse for row in matrix: row.reverse() Accepted by leetcode.

  • @almasmirzakhmetov8590

    @almasmirzakhmetov8590

    2 жыл бұрын

    excellent solution. By the way your solution is based on rotation matrix, right? For 90 degree, we have (x,y) -> (y,x) en.wikipedia.org/wiki/Rotation_matrix

  • @Rahul-pr1zr

    @Rahul-pr1zr

    2 жыл бұрын

    How do you even get the idea to transpose and then reverse? I agree that implementation is easier but the idea doesn't seem that simple.

  • @333jjjjjj

    @333jjjjjj

    2 жыл бұрын

    @@Rahul-pr1zr You need to recall it from your linear algebra class. Good luck if that was more than a few months ago or never.

  • @peterpace3379

    @peterpace3379

    2 жыл бұрын

    @@333jjjjjj for me it was a whole year ago lmao

  • @przemysawpobrotyn1195

    @przemysawpobrotyn1195

    2 жыл бұрын

    I have another solution in similar vein. I came up with it by eyeballing the leetcode provided input/output samples and noticing that the firs element of the last row of the input is the first element of the first row of the output, the second element of the last row of the input is the first element of the second row of the output etc. thus n = len(matrix) for row in matrix[::-1]: for i in range(n): element = row.pop(0) matrix[i].append(element) also does the job ;)

  • @doublegdog
    @doublegdog2 жыл бұрын

    Just got an offer at amazon. Your videos rock and helped me out so much!

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Congratulations 🎉

  • @xqfang3171
    @xqfang31712 жыл бұрын

    This is the best explanation for this problem. Crystal clear visualization, elegant code. Great job. Thank you so much for posting!

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Happy it was helpful! :)

  • @d1rtyharry378
    @d1rtyharry3782 жыл бұрын

    Bro what an structured approach . Really loved your way of teaching man! You made it look so easy.

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Thanks!

  • @lottexy
    @lottexy2 жыл бұрын

    I gotta say your videos are amazing. I've been grinding LC for the past 3 weeks, I went from struggling to solve even 1 question on the weekly leetcode contest to solving 2 - 3 questions each week. Thank you so much. I've also and will always share your videos and excel sheet on reddit whenever people ask for leetcode tips. Oh and its abit late but congrats on the Google offer! I hope to one day get into google as well or any other company tbh ( my current tech job kinda blows ) ...

  • @suraj8092

    @suraj8092

    2 жыл бұрын

    Good luck!

  • @annieonee
    @annieonee2 жыл бұрын

    This is the best explanation of this problem so I've found. Thank you so much for the content! Keep up the good work 👏

  • @MsSkip60
    @MsSkip603 жыл бұрын

    Thanks a lot for the content mate! No offence to others but I really like your clear accent and structured material which is easy to follow. Hope you keep up posting!

  • @sumosam1980
    @sumosam19803 жыл бұрын

    Your videos are excellent. You do a great job of being super clear! I often come here to Neetcode to see if you have the solution as it is better than the official explanation. Keep up the great work!

  • @sureshgarine
    @sureshgarine2 жыл бұрын

    I really like the way u handled minimizing the temp variable swap. very well explained. Thank you so much.

  • @jananiadanurrammohan9795
    @jananiadanurrammohan97952 жыл бұрын

    Best explanation one could ever give for a problem!!!. Thank you for the effort and time you are putting into making all these videos.

  • @ishaanjain4973
    @ishaanjain4973 Жыл бұрын

    I cant explain you how much this channel helps me !! Other channels just tell the transpose method which is not so intuitive, you always tell solutions which I can think in future in real interviews and exams. Thanks a lot Neetcode !! Keep up the good work man

  • @emanawel9224
    @emanawel92242 жыл бұрын

    This code makes the problem look way easier than it is! Love the code and explanation.

  • @chichiem2397
    @chichiem2397 Жыл бұрын

    These videos are great, this one in particular is perfect. I struggled with this a lot until I checked out this video. Awesome stuff!

  • @parthpatel8532
    @parthpatel85322 жыл бұрын

    Although this is a good way to do it, I found my way to be a bit simpler once you understand matrix manipulation. Rotating a matrix by 90⁰ is equivalent to flipping the matrix diagonally and then flipping it vertically. First try it out with paper, and once u get it, it's really easy. It doesn't save runtime or anything, but I find it easier in terms of code than to move 4 things at a time layer by layer.

  • @jim5621

    @jim5621

    Жыл бұрын

    Brilliant idea. But this solution takes 2x time since you need to loop through the matrix twice. But the time complexity is still O(n) though. Good thinking!

  • @brainmaxxing1

    @brainmaxxing1

    10 ай бұрын

    ​@@jim5621 "This solution takes 2x time" isn't actually true. Because of things like cache locality, where the elements that are in the same row will be closer to operate on for the CPU, it's not possible to say that the element-wise method is faster. The profiling method actually worked about 25% faster from tests on my computer!

  • @himanshubansal7040
    @himanshubansal7040 Жыл бұрын

    This is a beautiful way to write the code for this tricky problem. Kudos!!

  • @codewithtejesh1284
    @codewithtejesh12842 жыл бұрын

    thanks a lot, great explanation! i stopped my leetcode subscription , now i am just watching your videos and solving question.

  • @bruce716
    @bruce7162 жыл бұрын

    Thanks for the details and it is really easier to understand the concept with your good variable naming convention.

  • @jimmycheong7970
    @jimmycheong79702 жыл бұрын

    This is a freaking amazing explanation. Thank you so much for sharing!

  • @suhasdon1
    @suhasdon13 жыл бұрын

    Thank you. Best explanation without having to deal with 2 for loops with i, j or recursion and all other BS to be worried about.

  • @seungjunlee00
    @seungjunlee002 жыл бұрын

    Thank you so much for the straightforward and clear answer!

  • @Cruzylife
    @Cruzylife2 жыл бұрын

    wow this explanation was so clear and the code was so clean!!

  • @ElijahGeorge
    @ElijahGeorge2 жыл бұрын

    This is a very intuitive explanation. Thanks so much!!

  • @alinisar87
    @alinisar873 жыл бұрын

    Beautiful solution, great explanation. Thank you so much.

  • @mykytapiskarov7291
    @mykytapiskarov72912 жыл бұрын

    Amazing solution and explanaition! I spent about 2 hours trying to understand leetcode "Rotate group of 4" solution - but no luck. Here 15 minutes - and it's clear.

  • @nayanachandran7072
    @nayanachandran70722 жыл бұрын

    I must've have tried to understand this problem atleast 10 times and always failing to remember it. I now know I will never forget it! Thanks!

  • @nayandhabarde
    @nayandhabarde3 жыл бұрын

    Good work with comments and simplicity!

  • @jasonngan5747
    @jasonngan57472 жыл бұрын

    This is super useful, thanks for the great work!

  • @anooppatils
    @anooppatils2 жыл бұрын

    Awesome Explanation. Just loved it. Keep up the good work :)

  • @krishnateja6428
    @krishnateja64288 ай бұрын

    Cleanest explanation I have ever seen. Thank you!

  • @bondinthepond
    @bondinthepond2 жыл бұрын

    Amazing approach - very structured! and of course backed by great visualization!! You've got a subscriber, just based on this!! :)

  • @leonfeng4006
    @leonfeng40062 жыл бұрын

    please continue to make more videos, this channel is pure gold

  • @karthikjayaraman9646
    @karthikjayaraman96463 жыл бұрын

    Excellent article. Keep'em coming!

  • @bilalahmedkhan9518
    @bilalahmedkhan95182 жыл бұрын

    I thought this was a very though problem but you made it so easy for me. Thank you!

  • @dineshraj5957
    @dineshraj595711 ай бұрын

    The best explanation by far of the layer rotation method. Damn it. The best!!

  • @mr.anonymous6098
    @mr.anonymous60982 жыл бұрын

    Perfect Solution. When I first read the solution in the Cracking the coding interview book, I spent quite a lot of time and still could not understand it. You really simplified the logic which is so much easier to follow! Great Job, man

  • @ArunRampure
    @ArunRampure4 күн бұрын

    Have been struggling with coming up with an notion of using boundaries and using that i variable. Neet explanations for the neet code to write. Thanks for adding this.

  • @FreeMayaTutorials
    @FreeMayaTutorials3 жыл бұрын

    Thanks for posting, this is great!

  • @sanidhyax
    @sanidhyax25 күн бұрын

    This is so elegant. Have solved multiple of 2d array problems but never thought of accessing the rows literally by [bottom[[R] and [top][L]

  • @akifozkan5065
    @akifozkan50652 жыл бұрын

    made it look like so simple, great explanation

  • @sanketkoli8641
    @sanketkoli8641 Жыл бұрын

    Very nice explanation. Thanks NeetCode!

  • @reaiswaryaa
    @reaiswaryaa2 жыл бұрын

    Wow what an amazing explanation. Thank you !

  • @nikiforovsansanich
    @nikiforovsansanich2 жыл бұрын

    Perfect explanation! Thank you!

  • @ChocolateMilkCultLeader
    @ChocolateMilkCultLeader2 жыл бұрын

    Your code was really elegant. Well done

  • @TheMzbac
    @TheMzbac2 жыл бұрын

    Very clearly explained, thank you

  • @yabgdouglas6032
    @yabgdouglas603211 ай бұрын

    my ego has made me attempt this problem almost 3 hours - thank you for this clean explanation!

  • @niteshsetin
    @niteshsetin2 жыл бұрын

    The explanation was awesome and helpful to understand the problem effectively. I was waiting to see the final input output but nevertheless the code is correct so i guess i will write and check myself 😁😊

  • @dollyvishwakarma2
    @dollyvishwakarma22 жыл бұрын

    No doubt I love your simple algos but this one can be done in a much simpler way which is to reverse the matrix row wise and then swapping the elements like we do for a transpose. Kudos to the great work you do :)

  • @user-xg2wj4dy5f

    @user-xg2wj4dy5f

    Жыл бұрын

    But to do that you will have to create another matrix which is the copy of the Matrix which is to be transposed and that is against the constraints of the question you have to work in the same Matrix

  • @harishsn4866
    @harishsn4866 Жыл бұрын

    Thank you so much. You're the best.

  • @algorithmimplementer415
    @algorithmimplementer4152 жыл бұрын

    This is the best explanation!!

  • @yasharma2301
    @yasharma23012 жыл бұрын

    Knew the O(2*n^2) solution using transpose followed by inversion, thanks for this great one pass solution.

  • @anxonpues6018
    @anxonpues6018Ай бұрын

    Good, explanation, improoving steps ... really golden pedagogical

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg Жыл бұрын

    Another great explanation my dude !

  • @suvrobanerjee2399
    @suvrobanerjee2399 Жыл бұрын

    Thanks for such a clear explanation.

  • @itspete2444
    @itspete24444 ай бұрын

    "This is still a square if you tilt your head enough" - that got me laughing harder than it should have

  • @PavelBogart
    @PavelBogart2 жыл бұрын

    love it. thank you!

  • @vaibhavkhanna2922
    @vaibhavkhanna2922 Жыл бұрын

    Great approach! Here you can see if you are confused with variable naming I have used some easy to understand names.Approach is still the same. void rotate(vector &matrix) { int size = matrix.size(); int startRow = 0; int startColumn = 0; int endRow = matrix.size() - 1; int endColumn = matrix.size() - 1; while (startRow { int current_column_for_start_row = startColumn; int current_row_for_end_Column = startRow; int current_column_for_end_row = endColumn; int current_row_for_start_column = endRow; int current_size = endColumn - startColumn; for (int i = 0; i { int temp = matrix[startRow][current_column_for_start_row]; matrix[startRow][current_column_for_start_row] = matrix[current_row_for_start_column][startColumn]; matrix[current_row_for_start_column][startColumn] = matrix[endRow][current_column_for_end_row]; matrix[endRow][current_column_for_end_row] = matrix[current_row_for_end_Column][endColumn]; matrix[current_row_for_end_Column][endColumn] = temp; current_column_for_start_row++; current_row_for_end_Column++; current_column_for_end_row--; current_row_for_start_column--; } startRow++; startColumn++; endRow--; endColumn--; } }

  • @pengmick2046
    @pengmick2046 Жыл бұрын

    Your explanation is so good

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk2 жыл бұрын

    Nice, explanation. I thought the same thing but got thrown off on how to get the indexes

  • @AshishSarin1
    @AshishSarin12 жыл бұрын

    Thanks for this explanation. Really liked it.

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Thank you so much!! Glad it was helpful!

  • @navenkumarduraisamy6260
    @navenkumarduraisamy62603 жыл бұрын

    I really wish I had such clear approach

  • @kwaminaessuahmensah8920
    @kwaminaessuahmensah89202 жыл бұрын

    Mans went into god mode swapping the elements in reverse

  • @Omar-hw7zi
    @Omar-hw7zi3 жыл бұрын

    WOW, really neat!!

  • @aaronpuah918
    @aaronpuah9182 жыл бұрын

    You really are the Bob Ross of LeetCode XD

  • @nilkamalthakuria4030
    @nilkamalthakuria40303 жыл бұрын

    Great explanation

  • @suchitranagarajan7715
    @suchitranagarajan77152 жыл бұрын

    Great explanation!!!

  • @pleasedontsubscribeme4397
    @pleasedontsubscribeme43972 жыл бұрын

    Best of the best solution!

  • @eugenesol2074
    @eugenesol20742 ай бұрын

    Nice, thanks for that

  • @hunglam2680
    @hunglam26802 жыл бұрын

    thank you. this problem has been bugging me, i figured out how to rotate the image but couldn't implement it properly.

  • @rahulsreedharan1922
    @rahulsreedharan19222 жыл бұрын

    Great video. Just one question - why are the elements replaced in a counterclockwise manner? What benefit does it have over the more intuitive way of just replacing it clockwise?

  • @collinskariuki2586
    @collinskariuki25862 жыл бұрын

    Hey. Thank you for the explanation. Query: In your drawing, you portray the bottom pointer moving up and the top pointer moving down, so it's kinda confusing for me because in your code you write 'bottom - i' and 'top + i'. Mind explaining this distinction?

  • @stith_pragya
    @stith_pragya Жыл бұрын

    Thank You Brother for this amazing video.............🙏🙏🙏🙏🙏🙏

  • @ledinhanhtan
    @ledinhanhtan Жыл бұрын

    Beautiful code~

  • @RandomShowerThoughts
    @RandomShowerThoughts Жыл бұрын

    very intuitive

  • @harishdukkipati8921
    @harishdukkipati8921 Жыл бұрын

    Your explanation is very clear and I understand how it works. However, when I try it on leetcode it says my time limit is exceeded. Would you have any reason for why that would be the case.

  • @dinamohamed13600
    @dinamohamed13600 Жыл бұрын

    fantastic teacher!

  • @nareshnaklak6111
    @nareshnaklak61113 жыл бұрын

    awesome explanation.. thanks (Y)

  • @user-dk5mu4qp4s
    @user-dk5mu4qp4s2 жыл бұрын

    You are so genius!!

  • @Raj_Patel21
    @Raj_Patel213 жыл бұрын

    Awesome !!!!

  • @huimingli9207
    @huimingli9207 Жыл бұрын

    This is really a pure math problem. rotating a cell 90 degree, the index/coordinate change is from (x,y) -> (y, n-1-x).

  • @wij8044
    @wij80448 ай бұрын

    Easier solution for nXn matrix! Neetcode solution may be better suited for nXm matrix. function rotate(matrix: number[][]): void { const n = matrix.length; // Transpose the matrix, starting from i = 1 for (let i = 1; i for (let j = i; j [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; } } // Reverse each row for (let i = 0; i matrix[i].reverse(); } }

  • @prankobano9076
    @prankobano9076 Жыл бұрын

    Cool beans dude!

  • @sunnyding602
    @sunnyding602 Жыл бұрын

    Thanks for the clear explanation. I can understand it while I am in a food coma. lol

  • @TechOnScreen
    @TechOnScreen Жыл бұрын

    amazing !

  • @ethanking123
    @ethanking1238 ай бұрын

    Could you provide a C++ solution? The C++ approach on your website appears to be a direct copy from LeetCode, which differs from the demonstration in this video

  • @prithvini04
    @prithvini042 жыл бұрын

    video is so helpful.

  • @DanielTruongDev
    @DanielTruongDev2 жыл бұрын

    Great explanation, however if you recalled from Linear Algebra, this is basically transpose the matrix so (row,col) becomes (col,row). So here's a shorter solution in Python rows = len(matrix) matrix.reverse() #Reverse the matrix for r in range(rows): for c in range(r,rows): matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c] #Transpose

  • @MahfujurRahmanAraf
    @MahfujurRahmanAraf Жыл бұрын

    Dude you are amazing

  • @NeetCode

    @NeetCode

    Жыл бұрын

    Thank you 🙏

  • @dillondalton2989
    @dillondalton29893 жыл бұрын

    beautiful code

  • @maamounhajnajeeb209
    @maamounhajnajeeb209 Жыл бұрын

    as usual, you made it easy man

  • @burburchacha
    @burburchacha7 ай бұрын

    I hope you realise that you have a gift in explaining difficult concepts

  • @Quantumstream
    @Quantumstream2 жыл бұрын

    Thanks!

  • @siddharthgupta6162
    @siddharthgupta61622 жыл бұрын

    This video is so so so (X100) much better than the leetcode's solutions on this problem.

  • @rentianxiang92
    @rentianxiang922 жыл бұрын

    you are awesome!

  • @pampanasubrahmanyam5693
    @pampanasubrahmanyam56932 жыл бұрын

    small correction, in the for loop, at the range function it should be range(r) not range(r-1) for python3

  • @rohatgiy

    @rohatgiy

    2 жыл бұрын

    bro it’s an L

  • @franly656
    @franly6569 ай бұрын

    hi neetcode, i have a question, how to rotate matrix 45 degrees so the matrix size will increase, i trying to make the solution and now i want to give up (i have tried straight 5 hours btw). Can you make this solution a video pls.

  • @menzeus4293
    @menzeus42932 жыл бұрын

    genius solution!

  • @Michael-zh3op
    @Michael-zh3op25 күн бұрын

    After playing around with matrices, this question was a cake walk.

  • @ashinshenoy84
    @ashinshenoy842 жыл бұрын

    Very well explained, but i spotted one line which could be shifted up. Line 10 can be put before the for loop isnt it ? no need to initialize it on every loop

Келесі