DEV Community

Debesh P.
Debesh P.

Posted on

48. Rotate Image | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/rotate-image/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/rotate-image/solutions/7467003/smartest-solution-ever-most-optimized-co-xp8k


leetcode 48


Solution

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

        int n = matrix.length;

        // step 1: transpose the matrix
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

        // step 2: reverse each row
        for (int i = 0; i < n; i++) {
            int left = 0;
            int right = n - 1;
            while (left < right) {
                int temp = matrix[i][left];
                matrix[i][left] = matrix[i][right];
                matrix[i][right] = temp;
                left++;
                right--;
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)