Rotate Image - Matrix - Leetcode 48

Sdílet
Vložit
  • čas přidán 8. 07. 2024
  • 🚀 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.
  • Věda a technologie

Komentáře • 282

  • @NeetCode
    @NeetCode  Před 2 lety +15

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

  • @meowmaple
    @meowmaple Před 2 lety +217

    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 Před 2 lety +4

      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 Před 2 lety +25

      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 Před 2 lety +33

      @@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 Před 2 lety

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

    • @przemysawpobrotyn1195
      @przemysawpobrotyn1195 Před rokem +3

      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 ;)

  • @srinadhp
    @srinadhp Před 2 lety +198

    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 Před 2 lety +7

      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 Před 2 lety +2

      @@sidkapoor9085 mind blown

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

      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 Před rokem

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

    • @princeanthony8525
      @princeanthony8525 Před rokem

      Same here.

  • @doublegdog
    @doublegdog Před 2 lety +147

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

  • @sanidhyax
    @sanidhyax Před 10 dny

    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]

  • @MsSkip60
    @MsSkip60 Před 3 lety +107

    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!

  • @xqfang3171
    @xqfang3171 Před 2 lety +12

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

    • @NeetCode
      @NeetCode  Před 2 lety +1

      Happy it was helpful! :)

  • @d1rtyharry378
    @d1rtyharry378 Před 2 lety +28

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

  • @annieonee
    @annieonee Před 2 lety +3

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

  • @lottexy
    @lottexy Před 2 lety +12

    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 ) ...

  • @jananiadanurrammohan9795
    @jananiadanurrammohan9795 Před 2 lety +2

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

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

    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
    @sureshgarine Před 2 lety +1

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

  • @ishaanjain4973
    @ishaanjain4973 Před rokem

    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
    @emanawel9224 Před 2 lety +2

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

  • @parthpatel8532
    @parthpatel8532 Před rokem +13

    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 Před rokem +1

      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 Před 10 měsíci +1

      ​@@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!

  • @chichiem2397
    @chichiem2397 Před rokem

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

  • @himanshubansal7040
    @himanshubansal7040 Před rokem

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

  • @seungjunlee00
    @seungjunlee00 Před 2 lety +1

    Thank you so much for the straightforward and clear answer!

  • @codewithtejesh1284
    @codewithtejesh1284 Před 2 lety +1

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

  • @jimmycheong7970
    @jimmycheong7970 Před 2 lety +2

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

  • @ElijahGeorge
    @ElijahGeorge Před 2 lety +1

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

  • @bruce716
    @bruce716 Před 2 lety

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

  • @Cruzylife
    @Cruzylife Před 2 lety +2

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

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

    Beautiful solution, great explanation. Thank you so much.

  • @jasonngan5747
    @jasonngan5747 Před 2 lety

    This is super useful, thanks for the great work!

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

    Good work with comments and simplicity!

  • @mykytapiskarov7291
    @mykytapiskarov7291 Před 2 lety

    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.

  • @krishnateja6428
    @krishnateja6428 Před 8 měsíci

    Cleanest explanation I have ever seen. Thank you!

  • @nayanachandran7072
    @nayanachandran7072 Před 2 lety

    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!

  • @anooppatils
    @anooppatils Před 2 lety

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

  • @suhasdon1
    @suhasdon1 Před 3 lety +4

    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.

  • @karthikjayaraman9646
    @karthikjayaraman9646 Před 3 lety

    Excellent article. Keep'em coming!

  • @bondinthepond
    @bondinthepond Před 2 lety +1

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

  • @dineshraj5957
    @dineshraj5957 Před 10 měsíci

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

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

    Thanks for posting, this is great!

  • @leonfeng4006
    @leonfeng4006 Před 2 lety

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

  • @bilalahmedkhan9518
    @bilalahmedkhan9518 Před rokem

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

  • @nikiforovsansanich
    @nikiforovsansanich Před rokem +1

    Perfect explanation! Thank you!

  • @sanketkoli8641
    @sanketkoli8641 Před rokem

    Very nice explanation. Thanks NeetCode!

  • @mr.anonymous6098
    @mr.anonymous6098 Před 2 lety +1

    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

  • @PavelBogart
    @PavelBogart Před 2 lety

    love it. thank you!

  • @Michael-zh3op
    @Michael-zh3op Před 11 dny

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

  • @anxonpues6018
    @anxonpues6018 Před 16 dny

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

  • @reaiswaryaa
    @reaiswaryaa Před 2 lety

    Wow what an amazing explanation. Thank you !

  • @akifozkan5065
    @akifozkan5065 Před 2 lety

    made it look like so simple, great explanation

  • @yabgdouglas6032
    @yabgdouglas6032 Před 11 měsíci

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

  • @vaibhavkhanna2922
    @vaibhavkhanna2922 Před rokem

    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 < endRow && startColumn < endColumn)
    {
    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 < current_size; 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--;
    }
    }

  • @ChocolateMilkCultLeader

    Your code was really elegant. Well done

  • @TheMzbac
    @TheMzbac Před 2 lety

    Very clearly explained, thank you

  • @algorithmimplementer415

    This is the best explanation!!

  • @wij8044
    @wij8044 Před 8 měsíci

    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 < n; i++) {
    for (let j = i; j < n; j++) {
    [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
    }
    }
    // Reverse each row
    for (let i = 0; i < n; i++) {
    matrix[i].reverse();
    }
    }

  • @harishsn4866
    @harishsn4866 Před rokem

    Thank you so much. You're the best.

  • @kwaminaessuahmensah8920
    @kwaminaessuahmensah8920 Před 2 lety +2

    Mans went into god mode swapping the elements in reverse

  • @suvrobanerjee2399
    @suvrobanerjee2399 Před rokem

    Thanks for such a clear explanation.

  • @dollyvishwakarma2
    @dollyvishwakarma2 Před 2 lety +2

    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 Před rokem +3

      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

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg Před rokem

    Another great explanation my dude !

  • @yasharma2301
    @yasharma2301 Před 2 lety

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

  • @Omar-hw7zi
    @Omar-hw7zi Před 3 lety +1

    WOW, really neat!!

  • @huimingli9207
    @huimingli9207 Před rokem +1

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

  • @niteshsetin
    @niteshsetin Před 2 lety

    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 😁😊

  • @aaronpuah918
    @aaronpuah918 Před 2 lety

    You really are the Bob Ross of LeetCode XD

  • @suchitranagarajan7715

    Great explanation!!!

  • @DanielTruongDev
    @DanielTruongDev Před 2 lety

    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

  • @itspete2444
    @itspete2444 Před 3 měsíci

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

  • @pleasedontsubscribeme4397

    Best of the best solution!

  • @pengmick2046
    @pengmick2046 Před rokem

    Your explanation is so good

  • @Blobtheblobfish
    @Blobtheblobfish Před 3 lety +3

    Here is a js solution
    const rotate = (matrix) => {
    let left = 0;
    // number of columns - 1,
    // also think, actual position of right
    let right = matrix.length - 1;

    while (left < right) {
    for (let i = 0; i < right - left; i++) {
    let top = left;
    let bottom = right;

    let topLeft = matrix[top][left + i];

    matrix[top][left + i] = matrix[bottom - i][left];

    matrix[bottom - i][left] = matrix[bottom][right - i];

    matrix[bottom][right - i] = matrix[top + i][right];

    matrix[top + i][right] = topLeft;

    }
    left++;
    right--;
    }
    };
    yes I know, py and JS are about as close to languages as you can get but for anyone new or may not understand the small differences between py and JS, here is your answer. NeetCode, thank you, your explanation was thorough and also less than 15 minutes which is great.

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

    Great explanation

  • @AshishSarin1
    @AshishSarin1 Před 2 lety

    Thanks for this explanation. Really liked it.

    • @NeetCode
      @NeetCode  Před 2 lety +1

      Thank you so much!! Glad it was helpful!

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

    I really wish I had such clear approach

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

    Awesome !!!!

  • @eugenesol2074
    @eugenesol2074 Před 2 měsíci

    Nice, thanks for that

  • @ledinhanhtan
    @ledinhanhtan Před rokem

    Beautiful code~

  • @IncrementalNova
    @IncrementalNova Před 2 lety +23

    Great content Bro :)
    Solution in Java:
    class Solution {
    public void rotate(int[][] matrix) {
    int n = matrix.length;
    int right=n-1, left=0;
    //neetcode solution video
    while(left

    • @sebastian_tec
      @sebastian_tec Před 2 lety +3

      @theraplounge because as you enter in the inner loops the offset, or the amout that you have to add/subtract for the rotation decreases. in the video for the outer matrix the offset can be as much as 2, but in the inner matrix that offset is 0.

    • @inspiredomkar1239
      @inspiredomkar1239 Před rokem

      Thanks. I was looking for it.

  • @dinamohamed13600
    @dinamohamed13600 Před rokem

    fantastic teacher!

  • @RandomShowerThoughts
    @RandomShowerThoughts Před rokem

    very intuitive

  • @user-dk5mu4qp4s
    @user-dk5mu4qp4s Před 2 lety

    You are so genius!!

  • @stith_pragya
    @stith_pragya Před rokem

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

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk Před 2 lety

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

  • @symbol767
    @symbol767 Před 2 lety +3

    This shows me how many people in the comments don't even try the solution themselves.
    I tried the solution in this video on leetcode and it doesn't pass the test cases.

  • @sunnyding602
    @sunnyding602 Před rokem

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

  • @rahulsreedharan1922
    @rahulsreedharan1922 Před 2 lety

    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?

  • @dr.merlot1532
    @dr.merlot1532 Před 2 lety

    The guys talking about transpose mean this: Geometrically, rotation of the plane by 90 degrees is equivalent to flipping about the diagonal line y=-x and then flipping about the y-axis. That's why this works.

  • @TechOnScreen
    @TechOnScreen Před rokem

    amazing !

  • @prankobano9076
    @prankobano9076 Před rokem

    Cool beans dude!

  • @prithvini04
    @prithvini04 Před 2 lety

    video is so helpful.

  • @burburchacha
    @burburchacha Před 7 měsíci

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

  • @siddharthgupta6162
    @siddharthgupta6162 Před 2 lety

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

  • @collinskariuki2586
    @collinskariuki2586 Před rokem

    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?

  • @rentianxiang92
    @rentianxiang92 Před 2 lety

    you are awesome!

  • @johnlocke4695
    @johnlocke4695 Před 2 lety +1

    There is no way I could have figured this out myself. Not even if they give me a million years time.

  • @Quantumstream
    @Quantumstream Před 2 lety

    Thanks!

  • @welcomb
    @welcomb Před 2 lety +2

    There a very easy way to do this. First transpose the matrix, which is just flipping along a diagonal in-place. Then reflect vertically, which is another simple in-place swap.

    • @Qxismylife
      @Qxismylife Před 2 lety

      I am thinking about the same. But the problem is we don't know if this is allowed, at least for the purpose of what this question is examining. If this is allowed then you can also use the 2D rotation matrix too.

    • @Qxismylife
      @Qxismylife Před 2 lety

      Just saw other comments. This is allowed. I am happy now.

    • @welcomb
      @welcomb Před 2 lety

      @@Qxismylife using a 2D rotation matrix may not be inplace as you need extra space for the matrix. Transpose and flip can both be done inplace

  • @Tensor08
    @Tensor08 Před 2 lety +5

    I did this in one line 😎 which beats 97%
    matrix[:] = list(zip(*matrix[::-1]))

  • @josecarlosfontanesikling306

    It's possible to do this without any extra memory at all.
    Suppose you have variables x and y. You can swap them like this
    y=y+x
    x=y-x
    y=y-x
    This is all you need to transpose a matrix and to swap columns or rows. This rotation is just a transposition followed by inverting the order of the rows.

  • @maamounhajnajeeb209
    @maamounhajnajeeb209 Před rokem

    as usual, you made it easy man

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

    awesome explanation.. thanks (Y)

  • @dillondalton2989
    @dillondalton2989 Před 3 lety

    beautiful code

  • @_majortom_
    @_majortom_ Před 2 lety

    You don't need 'top', 'bottom', 'left' and 'right' mambo jumbo!
    Simplified transformation for clockwise rotation of [ X, Y ] is:
    [ X, Y ] => [ Y, abs(X - len(matrix) - 1) ]
    ...and for counterclockwise:
    [ X, Y ] => [ abs(Y - len(matrix) - 1), X ]
    i.e. (switch coordinates and replace one with the absolute value of itself minus the length of the matrix minus 1)
    Do all transformations from [ 0, 0 ] using TEMP variable, then walk diagonally toward the center... [ 1, 1 ], [ 2, 2 ], ...

    • @_majortom_
      @_majortom_ Před 2 lety

      Just to point out:
      whenever you see a 2D, 3D or nD rotation or translation challenge, you know there is ONE rule that works for all the nodes. There are no special cases in rotation nor in translation. Always try to find the rule instead of breaking the matrix into small pieces -> i.e. more challenges.