Rotate Matrix/Image by 90 Degrees | Brute - Optimal

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

КОМЕНТАРІ • 264

  • @takeUforward
    @takeUforward  Рік тому +14

    Please watch our new video on the same topic: ua-cam.com/video/Z0R2u6gd3GU/v-deo.html

  • @rudraprasad8912
    @rudraprasad8912 Рік тому +132

    The way you approach the problem.......It gives me the confidence that i can also do it!!!!!💀

  • @takeUforward
    @takeUforward  Рік тому +62

    Timestamps pleaseee.
    Let's march ahead, and create an unmatchable DSA course! ❤
    Use the problem links in the description.

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

      notes link is not visible

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

      Love you brother, marching ahead consistently.

  • @arjit1495
    @arjit1495 5 місяців тому +7

    Thanks. We can further improve by not using loop for reversing of row in optimal instead just use reverse after j loop is finished like this:
    for(int i = 0; i < n; i++)
    {
    for(int j = i + 1; j < n; j++)
    {
    swap(mat[i][j], mat[j][i]);
    }
    reverse(mat[i].begin(), mat[i].end());
    }

  • @alessandrocamilleri1239
    @alessandrocamilleri1239 Рік тому +23

    Great explanation.
    I tried to come up with my solution prior to watching the video. I used the intuition of concentric squares within the matrix. I traverse one side of each concentric square and perform three swaps for each element . Since only one side of each concentric square is traversed, the number of elements traversed is approximately 1/4(m*n) and since there are 3 swaps for each element the time complexity will be O(3/4 m*n). Using a swap counter, Striver's solution is very close to O(m*n).
    However, unlike Striver, I do use some extra auxiliary constant space in the form of 4 pairs of co-ordinates which I use to determine the correct placing of the elements during swapping.
    void rotate(vector& m)
    {
    int l = 0;
    int h = m.size() - 1;
    pair a, b, c, d;

    while (l < h)
    {
    a = {l,l}; b = {l,h}; c = {h,h}; d = {h,l};
    for (int i = l; i < h; i++)
    {
    swap (m[a.first][a.second], m[b.first][b.second]);
    swap (m[a.first][a.second], m[c.first][c.second]);
    swap (m[a.first][a.second], m[d.first][d.second]);
    a.second++; b.first++; c.second--; d.first--;
    }
    l++; h--;
    }
    }

  • @aman_singh__
    @aman_singh__ Рік тому +47

    TIMESTAMPS
    00:49 Problem statement
    2:06 Observation
    2:24 Brute force approach
    6:25 Brute force code
    7:49 Optimized approach
    14:00 pseudo code for transposition
    15:01 Optimized approach code

  • @riyadhossain1706
    @riyadhossain1706 Рік тому +20

    How you elaborate on the problem and solution is unique to any other free content I have gone through. I'll surely gonna recommend your channel if somebody asks.

  • @Karansingh17373
    @Karansingh17373 3 місяці тому +2

    we can also transpose as:
    for(int i=0;i

  • @sayantandey4708
    @sayantandey4708 Рік тому +15

    I did this optimal solution on my own, then came to see the solution video, this sheet building my confidence and skills little by little.
    (Rikon was my childhood friend. He worked for you some days back. No wonder why he praised you so much.)

  • @anuragprasad6116
    @anuragprasad6116 9 місяців тому +1

    I used the idea of concentric squares to solve the problem. Say, n = 6. Now the square will be of 3X3 size. You can draw a matrix to see how the outer square is of length = 6, inside it there's a square of side = 4 and inside it there's another square of side = 2. Basically each inside square is of 2 units lesser length then its outer square. We traverse from outside to inside and rotate each square one by one.
    For rotation, we traverse the upper side of the square and use 3 swaps for each grid. Also, the traversal is done till 2nd last grid because if you do the dry run, you'll notice that the last grid is already swapped in the first step, i.e., the corners are common between 2 given sides. The most difficult part is to deduce the co-ordinates for the replacing element. Imagine a square which you're traversing on its top side. Now, the top left element will be replaced by bottom left, bottom left by bottom right, bottom right by top right and top right by top left. It's hard to explain in a comment how I arrived at the co-ordinates but if someone wants to try this out, instead of swapping element by element, first try swapping row by row. I've attached codes for both. Basically, store the upper side of square in a temp array then replace top row with left column, replace left column with bottom row and so on. Once you understand how that's working, the co-ordinates for element by element swap is same but using lesser extra space. If someone needs a video explanation, do reply and I'll try to post a video explaining the same.
    // Swapping row by row:
    for (int i = 0; i < n/2; i++) {
    vector temp;
    for (int j = i; j < m-i; j++) temp.push_back(mat[i][j]);
    for (int j = m-i-1; j >= i; j--) mat[i][j] = mat[n-1-j][i];
    for (int j = m-i-1; j >= i; j--) mat[n-1-j][i] = mat[n-1-i][m-1-j];
    for (int j = m-i-1; j >= i; j--) mat[n-1-i][m-1-j] = mat[j][m-1-i];
    for (int j = m-i-1; j >= i; j--) mat[j][m-1-i] = temp[j-i];
    }
    // Swapping element by element
    int len = mat.size();
    for (int i = 0; i < len/2; i++) {
    for (int j = i; j < (len-i-1); j++) {
    int temp = mat[i][j];
    mat[i][j] = mat[len-1-j][i];
    mat[len-1-j][i] = mat[len-1-i][len-1-j];
    mat[len-1-i][len-1-j] = mat[j][len-1-i];
    mat[j][len-1-i] = temp;
    }
    }

  • @JohnCena-uf8sz
    @JohnCena-uf8sz 3 місяці тому +3

    I am watching in sequence, the best explanation frrrr.. SOME ONE REMIND ME TO STUDY BY LIKING THE COMMENT

  • @shubhamagarwal1434
    @shubhamagarwal1434 3 місяці тому

    #Free Education For All.. # Bhishma Pitamah of DSA...You could have earned in lacs by putting it as paid couses on udamey or any other elaerning portals, but you decided to make it free...it requires a greate sacrifice and a feeling of giving back to community, there might be very few peope in world who does this...."विद्या का दान ही सर्वोत्तम दान होता है" Hats Off to you man, Salute from 10+ yrs exp guy from BLR, India.

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

    Nice explaination, the best part is that you teach how to build your mind to think in that way.....

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

    Best optimal explaination with in depth time complexity. Great. I do by myself with rotated by anti-clockwise and clockwise both. THankyou

  • @umeshkaushik710
    @umeshkaushik710 Рік тому +4

    Thanks a lot bhaiya. This time I must say you are on fire. Your explaining capability is next level, bez I had problems in understanding the matrix(index and all). But Now super clear. OP Striver Guru 🔥🔥🔥🔥

  • @MihirAnand-w2q
    @MihirAnand-w2q 4 місяці тому +1

    We can also find a pattern i.e. i -> j and then j -> n-i-1

  • @codedByAyush
    @codedByAyush 5 місяців тому +2

    Bhaiya, apka har solutions are just too OP and easy to understand 🔥🔥

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

    Understood.
    Thank you for this amazing content. I have tried many lectures but the way you approach the problem it seems extremely easy.

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

    best DSA sheet ever you are the god of DSA really

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

    bro I was able to come up with the brute force myself but the optimal solution is just too good and clever 😆

  • @mind9889
    @mind9889 4 місяці тому +1

    I also came up with the transpose approach very happy 😁😁

  • @Krishnayadav-fu3uv
    @Krishnayadav-fu3uv Рік тому +5

    very well understood, thank you for the great content ❤

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

    Brother you are awesome. The way you give the solutions of the problems and it very helpful for me to explain whole code(dry and run).🙏🙏

  • @khanra17
    @khanra17 10 місяців тому

    9:54
    We do transpose not because we need to convert rows into column.
    If we have a another matrix to store then we can do it directly instead of two steps.
    we do it so that we can swap elements.
    you can't do it directly.
    so do the extra step

  • @brajeshmohanty2558
    @brajeshmohanty2558 Рік тому +7

    now I understood why bhai chose c++ over java because u have to write so many function in java but in c++ u have stl :( . But bro i understood the question thanku :b

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

    SDE Sheet Day 2 Problem 1 Done!

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

    so amazing watching your videos and getting to know how one should change there mind to observe the problem.

  • @ghayoorhussain8930
    @ghayoorhussain8930 Рік тому +7

    Java Code:
    ```class Solution {
    public void rotate(int[][] matrix) {
    int n = matrix.length;

    // Transpose of Matrix
    for (int i = 0; i < n - 1; i++) {
    for (int j = i + 1; j < n; j++) {
    int temp = matrix[i][j];
    matrix[i][j] = matrix[j][i];
    matrix[j][i] = temp;
    }
    }

    // Reverse each row
    for (int i = 0; i < n; i++) {
    int left = 0, right = n - 1;
    while (left < right) {
    int temp = matrix[i][left];
    matrix[i][left] = matrix[i][right];
    matrix[i][right] = temp;
    left++;
    right--;
    }
    }
    }
    }```

  • @16_AIML_ABHYAMSHAW
    @16_AIML_ABHYAMSHAW 3 місяці тому

    We don't need to use another loop for reverse() , we can simply add the reverse() after every inner loop ends but within outer loop.

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

    this is how I wrote the transpose code
    for(int i=0; i< n ; i++){
    for(int j=i; j < n; j++){
    swap(matrix[i][j], matrix[j][i]);
    }
    }
    which is less confusing

    • @ast_karan128
      @ast_karan128 6 місяців тому

      bro this code is not optimal, because it this code u will traverse through all elements, and the code in the video is not traversing the diagonal element which reduce the time complexity

    • @rashi1662
      @rashi1662 6 місяців тому

      @@ast_karan128 thanks for pointing that out bro 🤜

    • @KrishnaKumar-b4m9p
      @KrishnaKumar-b4m9p Місяць тому

      this will not work because after this loop all the element will be in actual place only and the array will be reach to its initial state because u are swapping twice the same element and so after this loop ends and there will be no change...

  • @torishi82
    @torishi82 6 місяців тому +1

    Samaj aa gaya bhai. Thank you.

  • @himanshigupta3255
    @himanshigupta3255 Місяць тому +1

    ******* we can do by this approach here i have used the i variable to swap the value instead of iterating i+1 to n-1
    class Solution {
    public:
    void rotate(vector& matrix)
    {int n=matrix.size();
    int m=matrix[0].size();
    for(int i=0;i

  • @ddevarapaga5134
    @ddevarapaga5134 4 місяці тому +1

    Superb UNderstood

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

    Understood
    Thank you for this amazing lecture sir.

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

    Bhaiya ur amazing . How can one explain with soo much perfection man. Live long and keep making videos for us . Hope to meet you soon .

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

    Understood! Amazing explanation as always, thank you very much for your effort!!

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

    I never thought, this question was that simple :(
    Understood Striver, Thanks

  • @jatinsharma1595
    @jatinsharma1595 11 місяців тому

    Understood. Thank you Striver

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

    an approach i came up with, if you need to rotate clockwise, just swap elements at each layer anticlockwise
    void rotate(vector& matrix) {
    int n = matrix.size();
    for(int i=0; i

  • @vidushibhardwaj1415
    @vidushibhardwaj1415 7 місяців тому

    thankyou so muxh for these videos❤❤... and the problem link added is a different question, but in your dsa sheet its same

  • @neilkapadia7
    @neilkapadia7 10 місяців тому

    Understood!
    Amazing explanation!

  • @getakashverma19
    @getakashverma19 7 місяців тому

    hi, the solution provided in the sheet for java doesn't follow the same explanation, the logic is bit changed in it.
    Here, is the code following the explanation:
    class Solution {
    public void rotate(int[][] matrix) {
    int n = matrix.length, m = matrix[0].length;
    //Transpose
    for(int i =0; i

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

    Sir app bhut accha Padhte hoo.

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

    Hi bro! I came across this problem and the first two operations on my mind were transpose and reverse. As the problem requried it to be solved in O(1) space, I carefully examined if the sequence of these operations made any signifcant changes to the performance.
    What I did was to reverse the matrix (row-wise) first, then take a transpose.
    The first operation used n/2 iterations (for optimal reversing).
    The second operation used n*(n+1)/2 iterations (for optimal transpose).
    So the total number of iterations with optimization: (n(n + 1) + n)/2 = O(n^2 + n) = O(n^2)
    With transpose first and then reverse each row: (n(n+1) + n^2)/2 = O(n^2 + n^2) = O(n^2)
    It doesn't make a difference as our PCs are blazzingly fast, but I found it neat :)
    Thanks a lot! This series is amazing!♥♥

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

    I wish , I would have seen this video before makemytrip interview.. Thank you for great content.

    • @aryanmandi7748
      @aryanmandi7748 9 місяців тому

      they ask to complete the func in interview or just write pseudo code

  • @rishipandey123
    @rishipandey123 10 місяців тому

    Wow sir amazing and super easy explanation ❤❤❤😊

  • @mr_weird3680
    @mr_weird3680 7 місяців тому +1

    Thank you very much brother🙇

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

    Awesome Lecture Sir.................

  • @mariia-travels
    @mariia-travels Рік тому

    Thank you for work you do. Really helpful!

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

    thanks you sir, i easily understand how to transpose matrix inplace.

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

    Beautifully explained.

  • @divyanshthakur2026
    @divyanshthakur2026 Рік тому +4

    Happy Ram Navami Everyone 🚩

  • @RituSingh-ne1mk
    @RituSingh-ne1mk 11 місяців тому +1

    Understood!

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

    understood very well !

  • @computer_tech98
    @computer_tech98 11 місяців тому +1

    Thank you

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

    Hey Striver, the problem link and the video link doesn't match in the SDE sheet, please get it updated...

  • @ast_karan128
    @ast_karan128 6 місяців тому

    for left rotate the matrix to 90 degree just reverse the columns instead of rows and done

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

    striver so happy to learn with youuh

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

    understood!!🙇‍♂

  • @AkOp-bf9vm
    @AkOp-bf9vm 6 місяців тому

    i think swap part of optimal approach take time complexity of O(N * N/2) bcz first loop is running for n times and second N/2 times

  • @harshdiwase1941
    @harshdiwase1941 10 місяців тому

    great explanation

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

    TC for the first 2 nested for loops would be O(N*N/2) in my point of view?!

  • @elmo4672
    @elmo4672 7 місяців тому

    trying to pass first year of college : ( thank you : )

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

    your dedication 🙌🙌

  • @tamilmukbang3789
    @tamilmukbang3789 7 місяців тому

    understood. thank you so much bro

  • @DeepakKumar-oz5ky
    @DeepakKumar-oz5ky 11 місяців тому

    Thank u Bhaiya Very helpFul video

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

    Understood bhaiya!

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

    Great Explanation❤🙇‍♂✨🙏

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

    Understood bro. Thank you

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

    understood 🚴‍♂

  • @ABISHEK-r7k
    @ABISHEK-r7k 8 місяців тому

    UNDERSTOOD SIR

  • @ayushdhiman9378
    @ayushdhiman9378 Рік тому +4

    i think the time complexity of the optimal should be O(N) * O(N/2) + O(N) * O(N/2)

    • @thelightoffight7881
      @thelightoffight7881 11 місяців тому

      How is N/2 brother i don't understand can you explain

    • @theornament
      @theornament 9 місяців тому +1

      I thought that too. For the first loop, we still have to go through all of the rows except last one, which would be O(n). Now, for each row you go through, you will go through n - (i + 1) columns, which theoretically means you go through the later half of our matrix. This is why it is calculated as n/2.
      Then, when we loop through the rows and reverse them, we say we go through n rows and for each row we have to go loop through it to reverse them, which with the algorithm provided by Striver, it takes n/2.
      So, the answer would be in fact O(n * n/2) + O(n * n/2), which in simpler terms is O(n^2/2).

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

    Understood, thank you.

  • @AbhishekGupta-xz1gd
    @AbhishekGupta-xz1gd Рік тому

    Optimal Solution:
    class Solution {
    public void rotate(int[][] matrix) {

    int n = matrix.length - 1;
    int k = 0;
    while(k < n){
    for(int i = k ; i < n ; i++){
    int temp1 = matrix[i][n];
    matrix[i][n] = matrix[k][i];
    int temp2 = matrix[n][n-i+k];
    matrix[n][n-i+k] = temp1;
    temp1 = matrix[n-i+k][k];
    matrix[n-i+k][k] = temp2;
    matrix[k][i] = temp1;
    }
    k++;
    n--;
    }
    }
    }

  • @samuelfrank1369
    @samuelfrank1369 9 місяців тому

    Understood. Thanks a lot

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

    understood bhaiya

  • @utkarshpundeer07
    @utkarshpundeer07 16 днів тому

    Understood 👍

  • @shaikhnabeel728
    @shaikhnabeel728 12 днів тому

    I think built the most confusing program but works lol:
    public void rotate(int[][] matrix) {
    int n = matrix.length;
    for (int j = 0; j < n / 2; j++) {
    int size = n-2;
    if(j != 0){
    size = n-2-j;
    }
    for (int i = j; i

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

    Understood! Sir

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

    Thank you sir!..

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

    Try using slicing method

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

    great job bro

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

    Understood, thanks💚

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

    Understood very well

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 9 місяців тому

    Thank you bhaiya

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

    understood!

  • @per.seus._
    @per.seus._ Рік тому +1

    understood❤

  • @HassanAbbas-wy7wj
    @HassanAbbas-wy7wj 2 місяці тому

    marvellous

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

    Understood❤

  • @NonameNoname-f2t
    @NonameNoname-f2t 9 місяців тому

    UNDERSTOOD

  • @PankajSingh-pb4vs
    @PankajSingh-pb4vs 9 місяців тому

    Understood ❤

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

    understood.

  • @alheraahmad5481
    @alheraahmad5481 3 місяці тому

    understood!

  • @MohitKumar-o3l1u
    @MohitKumar-o3l1u 9 місяців тому

    Understood.

  • @sayanibiswas3741
    @sayanibiswas3741 6 місяців тому

    Thank you 🙏

  • @SatendraChauhan-ke5yr
    @SatendraChauhan-ke5yr 7 місяців тому

    thankyou so much sir

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

    Tried it in a slightly different way and managed to get rid of the reverse function. Any feedback is welcome!
    class Solution {
    public void rotate(int[][] m) {
    int l = m.length - 1;
    for (int i = 0; i < Math.ceil(l/2.0); i++) {
    for (int j = i; j < l - i; j++) {
    int topLeft = m[i][j];
    int topRight = m[j][l-i];
    int bottomRight = m[l-i][l-j];
    int bottomLeft = m[l-j][i];
    m[i][j] = bottomLeft;
    m[j][l-i] = topLeft;
    m[l-i][l-j] = topRight;
    m[l-j][i] = bottomRight;
    }
    }
    }
    }

  • @AbhishekKumar-cv1dh
    @AbhishekKumar-cv1dh Рік тому

    Understoooood 🔥😁

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

    understood
    please came up with string problems

  • @SYCOA12CHAITANYAASOLE
    @SYCOA12CHAITANYAASOLE 6 місяців тому

    Understood !!