Rotate Image - Matrix - Leetcode 48

Поділитися
Вставка
  • Опубліковано 26 лис 2024

КОМЕНТАРІ • 297

  • @NeetCode
    @NeetCode  2 роки тому +18

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

  • @meowmaple
    @meowmaple 2 роки тому +302

    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 роки тому +7

      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 роки тому +35

      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 роки тому +46

      @@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 роки тому +1

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

    • @przemysawpobrotyn1195
      @przemysawpobrotyn1195 2 роки тому +9

      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 3 роки тому +232

    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 роки тому +8

      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 роки тому +2

      @@sidkapoor9085 mind blown

    • @markomekjavic
      @markomekjavic 2 роки тому +9

      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.

  • @doublegdog
    @doublegdog 2 роки тому +184

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

    • @NeetCode
      @NeetCode  2 роки тому +25

      Congratulations 🎉

    • @JustinBieber38524
      @JustinBieber38524 2 місяці тому

      Hi hope you are doing good
      Can you please guide me how's your preparation looks like

  • @MsSkip60
    @MsSkip60 3 роки тому +112

    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 3 роки тому +15

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

    • @NeetCode
      @NeetCode  3 роки тому +1

      Happy it was helpful! :)

  • @parthpatel8532
    @parthpatel8532 2 роки тому +15

    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 Рік тому +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 Рік тому +3

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

  • @d1rtyharry378
    @d1rtyharry378 3 роки тому +33

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

  • @sanidhyax
    @sanidhyax 5 місяців тому

    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]

  • @lottexy
    @lottexy 2 роки тому +14

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

  • @mykytapiskarov7291
    @mykytapiskarov7291 2 роки тому

    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.

  • @vaibhavkhanna2922
    @vaibhavkhanna2922 2 роки тому

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

  • @suhasdon1
    @suhasdon1 3 роки тому +5

    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.

  • @emanawel9224
    @emanawel9224 2 роки тому +2

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

  • @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

  • @huimingli9207
    @huimingli9207 Рік тому +3

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

  • @jananiadanurrammohan9795
    @jananiadanurrammohan9795 2 роки тому +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.

  • @annieonee
    @annieonee 2 роки тому +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 👏

  • @codewithtejesh1284
    @codewithtejesh1284 3 роки тому +1

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

  • @nayanachandran7072
    @nayanachandran7072 2 роки тому

    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!

  • @kwaminaessuahmensah8920
    @kwaminaessuahmensah8920 3 роки тому +3

    Mans went into god mode swapping the elements in reverse

  • @DanielTruongDev
    @DanielTruongDev 2 роки тому

    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

  • @yabgdouglas6032
    @yabgdouglas6032 Рік тому

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

  • @wij8044
    @wij8044 Рік тому

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

  • @IncrementalNova
    @IncrementalNova 3 роки тому +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 2 роки тому +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 Рік тому

      Thanks. I was looking for it.

  • @sureshgarine
    @sureshgarine 3 роки тому +1

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

  • @AlfredPros
    @AlfredPros 2 місяці тому +1

    While the LeetCode problem doesn't want the cheat solution, I tried it anyway and do the following code.
    def rotate(self, matrix: List[List[int]]) -> None:
    mat = list(zip(*matrix[::-1]))
    for j in range(len(matrix)):
    for i in range(len(matrix[0])):
    matrix[j][i] = mat[j][i]
    This code performs almost as fast as the solution with a caveat that it uses more memory.

  • @ArunRampure
    @ArunRampure 4 місяці тому

    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.

  • @mhdzahir423
    @mhdzahir423 Місяць тому

    Broo! your explanation is fantastic! as a beginner, this whole and sole problem made me understand how to play with 2D matrix in any situation!

  • @himanshubansal7040
    @himanshubansal7040 2 роки тому

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

  • @sumosam1980
    @sumosam1980 3 роки тому +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!

  • @itspete2444
    @itspete2444 8 місяців тому

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

  • @mr.anonymous6098
    @mr.anonymous6098 2 роки тому +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

  • @dollyvishwakarma2
    @dollyvishwakarma2 2 роки тому +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 Рік тому +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

  • @dr.merlot1532
    @dr.merlot1532 2 роки тому

    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.

  • @welcomb
    @welcomb 2 роки тому +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 2 роки тому

      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 2 роки тому

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

    • @welcomb
      @welcomb 2 роки тому

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

  • @Ilmard99
    @Ilmard99 2 роки тому +1

    1) Invert the order of the rows
    2) Transpose

  • @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.

  • @Cruzylife
    @Cruzylife 2 роки тому +2

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

  • @dineshraj5957
    @dineshraj5957 Рік тому

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

  • @krishnateja6428
    @krishnateja6428 Рік тому

    Cleanest explanation I have ever seen. Thank you!

  • @zekonja90
    @zekonja90 2 роки тому

    C# solution:
    public void Rotate(int[][] matrix)
    {
    int n = matrix.Length;

    for (int i = 0; i < n; i++)
    {
    for (int j = i; j < n; j++)
    {
    int tmp = matrix[i][j];
    matrix[i][j] = matrix[j][i];
    matrix[j][i] = tmp;
    }
    Array.Reverse(matrix[i]);
    }

    }
    Cheers!

  • @burburchacha
    @burburchacha Рік тому

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

  • @jimmycheong7970
    @jimmycheong7970 2 роки тому +2

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

  • @calvin_713
    @calvin_713 9 днів тому

    Super duper helpful! This math question is tricky as hell...

  • @bilalahmedkhan9518
    @bilalahmedkhan9518 2 роки тому

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

  • @anxonpues6018
    @anxonpues6018 5 місяців тому

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

  • @Michael-zh3op
    @Michael-zh3op 5 місяців тому

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

  • @chichiem2397
    @chichiem2397 2 роки тому

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

  • @pampanasubrahmanyam5693
    @pampanasubrahmanyam5693 2 роки тому +2

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

    • @rohatgiy
      @rohatgiy 2 роки тому +1

      bro it’s an L

  • @leonfeng4006
    @leonfeng4006 2 роки тому

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

  • @bruce716
    @bruce716 2 роки тому

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

  • @johnlocke4695
    @johnlocke4695 2 роки тому +1

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

  • @maxwong4657
    @maxwong4657 8 місяців тому +1

    I use JS. The same code but doesnt work! can't pass the case 6. I checked many times and asked GPT, GPT gave the correct answer, but leetcode didnt. Can anyone pass the case 6 with JS?
    var rotate = function (matrix) {
    let left = 0
    let right = matrix.length - 1
    while (left < right) {
    for (let i = left; i < right; i++) {
    let top = left
    let bottom = right
    const 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--
    }
    };

  • @nayandhabarde
    @nayandhabarde 3 роки тому +1

    Good work with comments and simplicity!

  • @yasharma2301
    @yasharma2301 2 роки тому

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

  • @siddharthgupta6162
    @siddharthgupta6162 2 роки тому

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

  • @ElijahGeorge
    @ElijahGeorge 2 роки тому +1

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

  • @seungjunlee00
    @seungjunlee00 2 роки тому +1

    Thank you so much for the straightforward and clear answer!

  • @aaronpuah918
    @aaronpuah918 3 роки тому

    You really are the Bob Ross of LeetCode XD

  • @Kenny-st8cg
    @Kenny-st8cg Рік тому

    Since its python you can just do
    def rotate(self, matrix: List[List[int]]) -> None:
    n = len(matrix)
    l, r = 0, n - 1
    while l < r:
    top, bottom = l, r
    for i in range(r - l):
    (
    matrix[top + i][r],
    matrix[top][l + i],
    matrix[bottom - i][l],
    matrix[bottom][r - i]
    ) = (
    matrix[top][l + i],
    matrix[bottom - i][l],
    matrix[bottom][r - i],
    matrix[top + i][r]
    )
    r -= 1
    l += 1
    So theres no need for a temp variable, in that case we also wouldnt have to care about doing it in reverse.
    But I think readablitiy suffers a little

    • @brainmaxxing1
      @brainmaxxing1 Рік тому

      An even better solution to consider:
      n = len(matrix)
      # Transpose Matrix
      for i in range(n):
      for j in range(i, n):
      matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

      # Reverse Matrix
      for row in matrix:
      row.reverse()

    • @Kenny-st8cg
      @Kenny-st8cg Рік тому

      @@brainmaxxing1 Sure, but the TC of that solution is obviously much worse.
      For that solution theres no need for the second for loop either:
      n = len(matrix)
      for row in range(n):
      for col in range(row + 1, n):
      matrix[col][row], matrix[row][col] = matrix[row][col], matrix[col][row]
      matrix[row].reverse()

    • @brainmaxxing1
      @brainmaxxing1 Рік тому

      The time complexity of both solutions is the same, O(n^2). You do more 'operations' but the performance is actually better in my testing (somehow because of how the computer handles the more common operations of reversing a row and transposing a matrix)
      My notebook testing all 3 colab.research.google.com/drive/1laaMa1XLalAsShcoqENbbD5peb-PdCHo#scrollTo=QSThsieXZiCO
      Also nice on removing the second loop, that does speed it up.

  • @nikiforovsansanich
    @nikiforovsansanich 2 роки тому +1

    Perfect explanation! Thank you!

  • @ChocolateMilkCultLeader
    @ChocolateMilkCultLeader 2 роки тому

    Your code was really elegant. Well done

  • @alinisar87
    @alinisar87 3 роки тому +1

    Beautiful solution, great explanation. Thank you so much.

  • @voxel9470
    @voxel9470 2 місяці тому

    Apparently you can rotate by transposing the matrix and then flipping each row. I've seen that solution be better than the way you illustrated here I'm assuming because it's more cache friendly in the flip phase.

  • @sanketkoli8641
    @sanketkoli8641 Рік тому

    Very nice explanation. Thanks NeetCode!

  • @KarthikChintalaOfficial
    @KarthikChintalaOfficial 5 місяців тому

    Like the approach. But it's tedious to really remember and do it. I like the transposing and reversing using a 2 ptr approach to do this.

  • @pengmick2046
    @pengmick2046 Рік тому

    Your explanation is so good

  • @SarveshBhatnagar1214
    @SarveshBhatnagar1214 2 роки тому

    I found more two approaches to this, First one is to reverse the image and then transpose the resulting matrix (Easier). Other approach is to do this matrix[:] = zip(*matrix[::-1]) I don't really understand what's happening here so if someone understands, please do tell :) Thanks!

  • @bondinthepond
    @bondinthepond 2 роки тому +1

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

  • @akshaibaruah1720
    @akshaibaruah1720 2 роки тому +1

    literally my go to channel..well was it really asked by microsoft?...I solved it by taking its transpose and then reversing it which is in place but needs two traversal

  • @navenkumarduraisamy6260
    @navenkumarduraisamy6260 3 роки тому +1

    I really wish I had such clear approach

  • @zr60
    @zr60 3 роки тому

    Chances are , you will not be able to think of a solution such as the second one (the one that stores only 1 variable). It's better to practise for the solution for the first one (the one that stores 4 different variables).

  • @rohitkumaram
    @rohitkumaram 2 роки тому

    still your logic a more pythonic approach:
    class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
    l = 0
    r = len(matrix) -1
    while l

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk 2 роки тому

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

  • @sunnybambooflute
    @sunnybambooflute Рік тому

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

  • @UmaAbhinavHindu
    @UmaAbhinavHindu 22 дні тому

    Great solution. Thanks

  • @khatharrmalkavian3306
    @khatharrmalkavian3306 2 роки тому +1

    You know you can just swap instead of using a temporary.
    Walk through it:
    Swap TL with TR
    Swap TL with BR
    Swap TL with BL
    Shazam, the corners are rotated and aux space is O(0).

    • @trongthuong9581
      @trongthuong9581 2 роки тому

      How can u perform swap without temp variable xD

    • @khatharrmalkavian3306
      @khatharrmalkavian3306 2 роки тому +1

      @@trongthuong9581 There are two common methods and one other method that is CPU dependent:
      A) XOR swap:
      x ^= y
      y ^= x
      x ^= y
      B) Mathematical swap:
      x += y
      y = x - y
      x -= y
      C) x86 and x64 CPUs have the XCHG instruction, but it's likely to have the same performance as the other methods. Theoretically it would be faster since it can target a memory value directly, but doing so causes the CPU to lock all cores for synchronization, which is a massive performance hit. Operating just on registers, it has about 3 cycles of latency, which is similar to the XOR and mathematical methods.

  • @TheMzbac
    @TheMzbac 2 роки тому

    Very clearly explained, thank you

  • @reaiswaryaa
    @reaiswaryaa 2 роки тому

    Wow what an amazing explanation. Thank you !

  • @anandsrikumar007
    @anandsrikumar007 4 місяці тому

    I took a temp array, copied all columns into the rows of the temp array but in reverse order, finally, I iterated the temp array and replaced matrix[row] = temp_array[row]

  • @Tomab3
    @Tomab3 2 роки тому

    You can transpose the matrix in place and reverse each row to achieve the same result

  • @akifozkan5065
    @akifozkan5065 3 роки тому

    made it look like so simple, great explanation

  • @jeffnguyen91
    @jeffnguyen91 3 роки тому +2

    class Solution(object):
    def rotate(self, matrix):
    """
    :type matrix: List[List[int]]
    :rtype: None Do not return anything, modify matrix in-place instead.
    """
    n = len(matrix[0])
    for i in range(n):
    for j in range(i,n):
    tmp = matrix[i][j]
    matrix[i][j] = matrix[j][i]
    matrix[j][i] = tmp
    for i in range(n):
    matrix[i].reverse()

  • @niteshsetin
    @niteshsetin 2 роки тому

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

  • @alexeymelezhik6473
    @alexeymelezhik6473 Рік тому

    "top" and "bottom" variables are not necessary, one could replace them by "l" and "r"

    • @brainmaxxing1
      @brainmaxxing1 Рік тому

      Sure, but why sacrifice readability? The difference is very small in terms of memory usage

  • @eltonlobo8697
    @eltonlobo8697 3 роки тому

    There's another approach to this problem:
    -Swap the non-diagonal elements (Because we want to make rows columns and vice-versa)
    -Use two pointers, one at the first column and the other at the last column, swap column elements
    -Do the above step until the first pointer is no more lesser than the second pointer
    (Last 2 steps are just to swap columns)
    Code:
    class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
    """
    Do not return anything, modify matrix in-place instead.
    """
    n=len(matrix)
    r=0
    while (r

  • @FreeMayaTutorials
    @FreeMayaTutorials 3 роки тому +1

    Thanks for posting, this is great!

  • @Tensor08
    @Tensor08 3 роки тому +5

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

  • @shivaacharya7247
    @shivaacharya7247 2 роки тому +1

    Great explanation! For some weird reason, for loop with range(l, r) does not pass all test cases!

    • @markvaldez526
      @markvaldez526 2 роки тому

      My code isn't passing either...

    • @shivaacharya7247
      @shivaacharya7247 2 роки тому +3

      @@markvaldez526 range(l, r) doesn't work because we are iterating r - l times, not from l to r. For example, if l = 5, and r = 10, we need to run our for loop 5 times starting index from 0, 1, 2, 3, and 4 NOT from 5, 6, 7, 8, 9 which would be the case if we do range(5, 10).

    • @ugochukwustephenmbonu7974
      @ugochukwustephenmbonu7974 2 роки тому +1

      @@shivaacharya7247 thanks for explaining. Cleared it up for me!

  • @ashinshenoy84
    @ashinshenoy84 2 роки тому

    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

  • @Blobtheblobfish
    @Blobtheblobfish 3 роки тому +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.

  • @harishsn4866
    @harishsn4866 2 роки тому

    Thank you so much. You're the best.

  • @eltaylor778
    @eltaylor778 Рік тому +1

    Great explanation, does anyone know why the range has to be range(right- left) instead of range(left,right)? The range(left,right) works on many of the smaller test cases but does not work on many of the harder ones. Help!

    • @kritmok1875
      @kritmok1875 Рік тому

      that's because we always want to start the i with 0.
      let's take (2, 4) as an example
      range(2,4) return 2,3
      but range(4-2) return 0, 1

  • @ElectronToInterface
    @ElectronToInterface 3 роки тому

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

  • @plotfi1
    @plotfi1 Рік тому

    I find the standard rotation technique to be pretty frustrating to think about. Instead ive found its easier to invert the values on the diagonal then reverse the rows.

  • @nilkamalthakuria4030
    @nilkamalthakuria4030 3 роки тому +1

    Great explanation

  • @KaushikChavali
    @KaushikChavali Рік тому

    I like the intuitively named variables.

  • @soumavanag5025
    @soumavanag5025 3 роки тому +1

    That is why comments are so important

  • @khaleabhishek5023
    @khaleabhishek5023 Рік тому +2

    this code is not working now