Bird
Raised Fist0
Interview PrepmatricesmediumAmazonMicrosoftGoogleFacebook

Rotate Image (90° Clockwise)

Choose your preparation mode4 modes available
🎯
Rotate Image (90° Clockwise)
mediumMATRIXAmazonMicrosoftGoogle

Imagine you are developing a photo editing app and need to rotate images efficiently in-place without using extra memory.

💡 This problem involves manipulating a 2D matrix to rotate it 90 degrees clockwise. Beginners often struggle because it requires understanding matrix indices and how to transform positions without extra space.
📋
Problem Statement

Given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise) in-place. You must rotate the matrix without allocating another 2D matrix.

1 ≤ n ≤ 1000matrix[i][j] is an integerRotation must be done in-place with O(1) extra space
💡
Example
Input"[[1,2,3],[4,5,6],[7,8,9]]"
Output[[7,4,1],[8,5,2],[9,6,3]]

After rotation, the first row becomes the last column, the second row becomes the middle column, and so on.

  • 1x1 matrix → same matrix after rotation
  • 2x2 matrix → simple swap of corners and edges
  • Matrix with all identical elements → output same as input
  • Matrix with negative and zero values → rotation still applies
⚠️
Common Mistakes
Swapping elements twice during transpose

Matrix ends up unchanged or incorrectly rotated

✅ Only swap elements where j > i to avoid double swapping

Reversing columns instead of rows after transpose

Matrix rotates counterclockwise instead of clockwise

✅ Reverse each row, not column, to achieve clockwise rotation

Incorrect index calculations in layer-by-layer swaps

Elements get misplaced or overwritten, corrupting matrix

✅ Carefully compute offsets and boundaries for each layer and element

Using extra space when problem requires in-place rotation

Fails interview requirement or uses more memory than allowed

✅ Implement transpose + reverse or layer swaps to rotate in-place

Not handling edge cases like 1x1 matrix

Code may throw errors or behave unexpectedly

✅ Add checks or ensure loops handle small matrices gracefully

🧠
Brute Force (Using Extra Matrix)
💡 This approach uses an additional matrix to store the rotated result, which is easier to understand but uses extra space.

Intuition

Create a new matrix and place each element from the original matrix into its rotated position by mapping indices accordingly.

Algorithm

  1. Create a new n x n matrix to hold rotated values.
  2. For each element at position (i, j) in the original matrix, place it at (j, n - 1 - i) in the new matrix.
  3. Copy the new matrix back to the original matrix to reflect the rotation.
  4. Return or modify the original matrix in-place.
💡 This approach clearly shows how indices transform during rotation but requires extra space and copying back.
</>
Code
def rotate(matrix):
    n = len(matrix)
    rotated = [[0]*n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            rotated[j][n - 1 - i] = matrix[i][j]
    for i in range(n):
        for j in range(n):
            matrix[i][j] = rotated[i][j]

# Example usage
if __name__ == '__main__':
    mat = [[1,2,3],[4,5,6],[7,8,9]]
    rotate(mat)
    print(mat)
Line Notes
n = len(matrix)Determine the size of the square matrix for iteration limits
rotated = [[0]*n for _ in range(n)]Create a new matrix initialized with zeros to store rotated values
rotated[j][n - 1 - i] = matrix[i][j]Map each element to its rotated position based on index transformation
matrix[i][j] = rotated[i][j]Copy rotated values back to original matrix to achieve in-place effect
import java.util.Arrays;
public class RotateImage {
    public static void rotate(int[][] matrix) {
        int n = matrix.length;
        int[][] rotated = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                rotated[j][n - 1 - i] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = rotated[i][j];
            }
        }
    }
    public static void main(String[] args) {
        int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
        rotate(mat);
        System.out.println(Arrays.deepToString(mat));
    }
}
Line Notes
int n = matrix.length;Get matrix dimension for loops
int[][] rotated = new int[n][n];Allocate new matrix to hold rotated elements
rotated[j][n - 1 - i] = matrix[i][j];Assign rotated position for each element
matrix[i][j] = rotated[i][j];Overwrite original matrix with rotated values
#include <iostream>
#include <vector>
using namespace std;

void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    vector<vector<int>> rotated(n, vector<int>(n));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            rotated[j][n - 1 - i] = matrix[i][j];
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            matrix[i][j] = rotated[i][j];
        }
    }
}

int main() {
    vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
    rotate(mat);
    for (auto& row : mat) {
        for (auto val : row) cout << val << ' ';
        cout << '\n';
    }
    return 0;
}
Line Notes
int n = matrix.size();Capture matrix size for iteration
vector<vector<int>> rotated(n, vector<int>(n));Create new matrix to hold rotated elements
rotated[j][n - 1 - i] = matrix[i][j];Place element in rotated position using index mapping
matrix[i][j] = rotated[i][j];Copy rotated matrix back to original to simulate in-place
function rotate(matrix) {
    const n = matrix.length;
    const rotated = Array.from({length: n}, () => Array(n).fill(0));
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            rotated[j][n - 1 - i] = matrix[i][j];
        }
    }
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            matrix[i][j] = rotated[i][j];
        }
    }
}

// Example usage
const mat = [[1,2,3],[4,5,6],[7,8,9]];
rotate(mat);
console.log(mat);
Line Notes
const n = matrix.length;Determine matrix dimension for loops
const rotated = Array.from({length: n}, () => Array(n).fill(0));Initialize new matrix to store rotated values
rotated[j][n - 1 - i] = matrix[i][j];Assign each element to its rotated position
matrix[i][j] = rotated[i][j];Overwrite original matrix with rotated matrix values
⏱
Complexity
TimeO(n^2)
SpaceO(n^2)

We iterate over all n^2 elements twice: once to fill the rotated matrix and once to copy back.

💡 For n=10, this means about 200 operations; for n=1000, about 2 million operations and extra memory for the new matrix.
Interview Verdict: Accepted but uses extra space

This approach works but is not optimal due to extra memory usage; good for understanding rotation logic.

🧠
Transpose and Reverse Rows (In-Place)
💡 This approach rotates the matrix in-place by first transposing it and then reversing each row, saving space.

Intuition

Rotating 90 degrees clockwise is equivalent to transposing the matrix and then reversing each row.

Algorithm

  1. Transpose the matrix by swapping elements matrix[i][j] and matrix[j][i] for i < j.
  2. Reverse each row of the transposed matrix.
  3. The matrix is now rotated 90 degrees clockwise in-place.
💡 Understanding transpose and row reversal separately helps grasp the rotation without extra space.
</>
Code
def rotate(matrix):
    n = len(matrix)
    # Transpose
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    # Reverse each row
    for i in range(n):
        matrix[i].reverse()

# Example usage
if __name__ == '__main__':
    mat = [[1,2,3],[4,5,6],[7,8,9]]
    rotate(mat)
    print(mat)
Line Notes
n = len(matrix)Get matrix size for iteration limits
for j in range(i + 1, n):Only swap elements above diagonal to avoid double swapping
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]Swap elements to transpose matrix in-place
matrix[i].reverse()Reverse each row to complete the 90-degree clockwise rotation
import java.util.Arrays;
public class RotateImage {
    public static void rotate(int[][] matrix) {
        int n = matrix.length;
        // Transpose
        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;
            }
        }
        // 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--;
            }
        }
    }
    public static void main(String[] args) {
        int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
        rotate(mat);
        System.out.println(Arrays.deepToString(mat));
    }
}
Line Notes
int n = matrix.length;Capture matrix dimension
for (int j = i + 1; j < n; j++)Swap only elements above diagonal to transpose once
int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp;Perform in-place swap for transpose
while (left < right)Reverse each row by swapping elements from ends towards center
#include <iostream>
#include <vector>
using namespace std;

void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    // Transpose
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            swap(matrix[i][j], matrix[j][i]);
        }
    }
    // Reverse each row
    for (int i = 0; i < n; i++) {
        int left = 0, right = n - 1;
        while (left < right) {
            swap(matrix[i][left], matrix[i][right]);
            left++;
            right--;
        }
    }
}

int main() {
    vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
    rotate(mat);
    for (auto& row : mat) {
        for (auto val : row) cout << val << ' ';
        cout << '\n';
    }
    return 0;
}
Line Notes
int n = matrix.size();Get matrix size for loops
for (int j = i + 1; j < n; j++)Transpose by swapping only upper triangle elements
swap(matrix[i][j], matrix[j][i]);In-place swap to transpose matrix
while (left < right)Reverse each row by swapping elements from ends
function rotate(matrix) {
    const n = matrix.length;
    // Transpose
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; 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();
    }
}

// Example usage
const mat = [[1,2,3],[4,5,6],[7,8,9]];
rotate(mat);
console.log(mat);
Line Notes
const n = matrix.length;Determine matrix size for iteration
for (let j = i + 1; j < n; j++)Transpose by swapping elements above diagonal once
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];ES6 destructuring swap for in-place transpose
matrix[i].reverse();Reverse each row to complete rotation
⏱
Complexity
TimeO(n^2)
SpaceO(1)

We perform two passes over the n x n matrix: one for transpose and one for reversing rows, both O(n^2). No extra matrix is used.

💡 For n=10, about 200 operations; for n=1000, about 1 million operations but no extra memory needed.
Interview Verdict: Accepted and optimal in space

This is the preferred approach in interviews due to in-place rotation and clear logic.

🧠
Layer-by-Layer Rotation (In-Place Four-Way Swap)
💡 This approach rotates the matrix by moving elements in groups of four in each layer, simulating the rotation directly.

Intuition

Rotate the matrix layer by layer, swapping four elements at a time to their rotated positions without extra space.

Algorithm

  1. Iterate over each layer from outermost to innermost.
  2. For each element in the current layer, perform a four-way swap with its rotated counterparts.
  3. Repeat until all layers are rotated.
  4. The matrix is rotated 90 degrees clockwise in-place.
💡 This approach requires careful index calculations but avoids transpose and reversal steps.
</>
Code
def rotate(matrix):
    n = len(matrix)
    for layer in range(n // 2):
        first = layer
        last = n - 1 - layer
        for i in range(first, last):
            offset = i - first
            top = matrix[first][i]
            # left -> top
            matrix[first][i] = matrix[last - offset][first]
            # bottom -> left
            matrix[last - offset][first] = matrix[last][last - offset]
            # right -> bottom
            matrix[last][last - offset] = matrix[i][last]
            # top -> right
            matrix[i][last] = top

# Example usage
if __name__ == '__main__':
    mat = [[1,2,3],[4,5,6],[7,8,9]]
    rotate(mat)
    print(mat)
Line Notes
for layer in range(n // 2):Process matrix layer by layer from outside in
first = layer; last = n - 1 - layerDefine boundaries of current layer
for i in range(first, last):Iterate over elements in current layer's edge
matrix[i][last] = topComplete the four-way swap to rotate elements
import java.util.Arrays;
public class RotateImage {
    public static void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int layer = 0; layer < n / 2; layer++) {
            int first = layer;
            int last = n - 1 - layer;
            for (int i = first; i < last; i++) {
                int offset = i - first;
                int top = matrix[first][i];
                // left -> top
                matrix[first][i] = matrix[last - offset][first];
                // bottom -> left
                matrix[last - offset][first] = matrix[last][last - offset];
                // right -> bottom
                matrix[last][last - offset] = matrix[i][last];
                // top -> right
                matrix[i][last] = top;
            }
        }
    }
    public static void main(String[] args) {
        int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
        rotate(mat);
        System.out.println(Arrays.deepToString(mat));
    }
}
Line Notes
for (int layer = 0; layer < n / 2; layer++)Loop over each layer from outer to inner
int first = layer; int last = n - 1 - layer;Define current layer boundaries
int offset = i - first;Calculate offset within the layer for swaps
matrix[i][last] = top;Assign saved top element to its rotated position
#include <iostream>
#include <vector>
using namespace std;

void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    for (int layer = 0; layer < n / 2; layer++) {
        int first = layer;
        int last = n - 1 - layer;
        for (int i = first; i < last; i++) {
            int offset = i - first;
            int top = matrix[first][i];
            // left -> top
            matrix[first][i] = matrix[last - offset][first];
            // bottom -> left
            matrix[last - offset][first] = matrix[last][last - offset];
            // right -> bottom
            matrix[last][last - offset] = matrix[i][last];
            // top -> right
            matrix[i][last] = top;
        }
    }
}

int main() {
    vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
    rotate(mat);
    for (auto& row : mat) {
        for (auto val : row) cout << val << ' ';
        cout << '\n';
    }
    return 0;
}
Line Notes
for (int layer = 0; layer < n / 2; layer++)Iterate through each concentric square layer
int first = layer; int last = n - 1 - layer;Identify boundaries of current layer
int offset = i - first;Calculate relative position within layer for swaps
matrix[i][last] = top;Place saved top element into its rotated position
function rotate(matrix) {
    const n = matrix.length;
    for (let layer = 0; layer < Math.floor(n / 2); layer++) {
        const first = layer;
        const last = n - 1 - layer;
        for (let i = first; i < last; i++) {
            const offset = i - first;
            const top = matrix[first][i];
            // left -> top
            matrix[first][i] = matrix[last - offset][first];
            // bottom -> left
            matrix[last - offset][first] = matrix[last][last - offset];
            // right -> bottom
            matrix[last][last - offset] = matrix[i][last];
            // top -> right
            matrix[i][last] = top;
        }
    }
}

// Example usage
const mat = [[1,2,3],[4,5,6],[7,8,9]];
rotate(mat);
console.log(mat);
Line Notes
for (let layer = 0; layer < Math.floor(n / 2); layer++)Process each layer from outermost to inner
const first = layer; const last = n - 1 - layer;Define current layer boundaries
const offset = i - first;Calculate offset for element swaps within layer
matrix[i][last] = top;Complete the four-way swap by placing saved top element
⏱
Complexity
TimeO(n^2)
SpaceO(1)

Each element is moved exactly once in a four-way swap, covering all n^2 elements layer by layer.

💡 For n=10, about 100 operations per layer and 5 layers; total roughly 500 operations, no extra memory.
Interview Verdict: Accepted and optimal in space

This approach is efficient and direct but requires careful index management; good to know as an alternative.

📊
All Approaches - One-Glance Tradeoffs
💡 In interviews, the transpose + reverse rows approach is preferred for clarity and optimal space; brute force is good for explanation; layer swaps are an advanced alternative.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute Force (Extra Matrix)O(n^2)O(n^2)NoN/AMention only - never code due to extra space
2. Transpose and Reverse RowsO(n^2)O(1)NoN/APreferred approach to code in interviews
3. Layer-by-Layer Four-Way SwapO(n^2)O(1)NoN/AGood alternative to discuss or code if comfortable
💼
Interview Strategy
💡 Use this guide to understand the problem deeply, practice coding all approaches, and prepare to explain tradeoffs clearly in interviews.

How to Present

Clarify the problem and constraints with the interviewer.Explain the brute force approach using extra space to demonstrate understanding of rotation.Introduce the optimal in-place approach using transpose and reverse rows.Optionally discuss the layer-by-layer four-way swap as an alternative.Write clean, tested code and analyze time and space complexity.

Time Allocation

Clarify: 2min → Approach: 5min → Code: 10min → Test & Optimize: 3min. Total ~20min

What the Interviewer Tests

Interviewer tests your understanding of matrix transformations, in-place algorithms, and ability to optimize space while maintaining correctness.

Common Follow-ups

  • Rotate image counterclockwise → transpose and reverse columns
  • Rotate by 180 degrees → two 90-degree rotations or reverse rows and columns
💡 These follow-ups test your ability to adapt the rotation logic and understand matrix symmetries.
🔍
Pattern Recognition

When to Use

1) Input is a square matrix; 2) Asked to rotate 90 degrees; 3) In-place rotation required; 4) No extra matrix allowed

Signature Phrases

rotate the image by 90 degreesin-place rotationsquare matrix

NOT This Pattern When

Matrix transposition alone or spiral traversal problems which do not require rotation

Similar Problems

Rotate Image (90° Counterclockwise) - similar rotation but reversed directionRotate Matrix by 180 Degrees - double rotation or reverse rows and columns

Practice

(1/5)
1. You are given a matrix of integers. You need to find all elements that are the smallest in their row and simultaneously the largest in their column. Which approach guarantees an optimal solution to this problem?
easy
A. Use a brute force approach checking each element by scanning its entire row and column repeatedly.
B. Precompute the minimum value of each row and the maximum value of each column, then find elements matching both conditions in a single pass.
C. Apply a dynamic programming approach to store intermediate minimum and maximum values for submatrices.
D. Use a greedy approach by selecting the smallest element in each row and checking if it is the largest in its column.

Solution

  1. Step 1: Understand problem constraints

    The problem requires identifying elements that are simultaneously the minimum in their row and maximum in their column.
  2. Step 2: Evaluate approaches

    Brute force (A) is correct but inefficient. DP (C) is unnecessary overhead. Greedy (D) can fail if multiple minimums exist in a row but only one is maximum in its column. Precomputing row minimums and column maximums (B) allows a single pass to find all lucky numbers efficiently.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Precompute arrays then single pass -> optimal and correct [OK]
Hint: Precompute mins and maxes for single pass [OK]
Common Mistakes:
  • Assuming greedy selection per row suffices
  • Using DP unnecessarily
  • Brute force is too slow
2. You are given an m x n matrix. If an element is 0, you must set its entire row and column to 0 in-place without using extra space proportional to the matrix size. Which approach guarantees an optimal solution with O(1) additional space?
easy
A. Use a greedy approach that zeroes rows and columns immediately when a zero is found during iteration.
B. Use a brute force approach by creating a separate matrix to mark zero positions and then update the original matrix.
C. Use dynamic programming to store zero positions and propagate zeroes through the matrix.
D. Use the first row and first column of the matrix as flags to mark which rows and columns should be zeroed, then update the matrix accordingly.

Solution

  1. Step 1: Understand space constraints

    The problem requires in-place modification with O(1) extra space, so approaches using extra matrices or arrays are not optimal.
  2. Step 2: Identify the flagging technique

    Using the first row and first column as markers allows tracking which rows and columns to zero without extra space, enabling a single pass update.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    First row/column flagging is a classic O(1) space solution [OK]
Hint: Use matrix edges as flags to save space [OK]
Common Mistakes:
  • Zeroing rows/columns immediately loses info about other zeros
  • Using extra space arrays violates O(1) space constraint
  • Greedy zeroing fails when zeros appear after initial zeroing
3. Consider the following Python code snippet for validating a Sudoku board using bitmasking:
def isValidSudoku(board):
    rows = [0] * 9
    cols = [0] * 9
    boxes = [0] * 9
    for i in range(9):
        for j in range(9):
            if board[i][j] == '.':
                continue
            val = ord(board[i][j]) - ord('1')
            mask = 1 << val
            box_index = (i // 3) * 3 + (j // 3)
            if (rows[i] & mask) or (cols[j] & mask) or (boxes[box_index] & mask):
                return false
            rows[i] |= mask
            cols[j] |= mask
            boxes[box_index] |= mask
    return true

board = [
    ['5','3','.','.','7','.','.','.','.'],
    ['6','.','.','1','9','5','.','.','.'],
    ['.','9','8','.','.','.','.','6','.'],
    ['8','.','.','.','6','.','.','.','3'],
    ['4','.','.','8','.','3','.','.','1'],
    ['7','.','.','.','2','.','.','.','6'],
    ['.','6','.','.','.','.','2','8','.'],
    ['.','.','.','4','1','9','.','.','5'],
    ['.','.','.','.','8','.','.','7','9']
]

print(isValidSudoku(board))
What is the output of this code?
easy
A. true
B. false
C. Raises an exception due to invalid indexing
D. Returns null

Solution

  1. Step 1: Trace first few iterations

    All digits are unique in their rows, columns, and boxes; no mask conflicts occur.
  2. Step 2: Confirm no duplicates found

    Since no duplicates are detected, the function completes and returns true.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Standard valid Sudoku board returns true [OK]
Hint: No duplicates -> function returns true [OK]
Common Mistakes:
  • Misreading box index calculation
  • Assuming '.' causes errors
  • Confusing return values
4. Consider the following buggy code for maximum hourglass sum using sliding window. Which line contains the subtle bug that can cause incorrect results when all matrix values are negative?
def max_hourglass_sum_sliding(matrix):
    n = len(matrix)
    m = len(matrix[0])
    max_sum = 0  # Bug here

    for i in range(n - 2):
        current_sum = (matrix[i][0] + matrix[i][1] + matrix[i][2] +
                       matrix[i+1][1] +
                       matrix[i+2][0] + matrix[i+2][1] + matrix[i+2][2])
        if current_sum > max_sum:
            max_sum = current_sum

        for j in range(1, m - 2):
            current_sum -= (matrix[i][j-1] + matrix[i+1][j] + matrix[i+2][j-1])
            current_sum += (matrix[i][j+2] + matrix[i+1][j+1] + matrix[i+2][j+2])
            if current_sum > max_sum:
                max_sum = current_sum
    return max_sum
medium
A. Line initializing max_sum to 0
B. Line computing current_sum for initial hourglass
C. Line subtracting left column elements in sliding window
D. Line adding right column elements in sliding window

Solution

  1. Step 1: Understand initialization of max_sum

    Setting max_sum = 0 causes incorrect max when all values are negative, as max_sum never updates to negative sums.
  2. Step 2: Confirm other lines are correct

    Current_sum calculation and sliding window updates are correct; bug is only in initialization.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Proper initialization must be -inf to handle negative values [OK]
Hint: Initialize max_sum to -inf to handle negative values [OK]
Common Mistakes:
  • Initializing max_sum to 0
  • Misindexing sliding window updates
  • Forgetting to update max_sum after sliding
5. Suppose you need to transpose a non-square matrix (m x n) in-place, but the matrix is stored as a flat array in row-major order. Which approach correctly handles this scenario?
hard
A. Transpose in-place by swapping elements only in the upper triangle of the matrix.
B. Use the same in-place swapping approach as for square matrices, swapping elements symmetrically across the diagonal.
C. Create a new matrix of size n x m and copy elements accordingly, since in-place transpose is not possible for non-square matrices.
D. Use a recursive approach to swap elements in cycles to achieve in-place transpose.

Solution

  1. Step 1: Understand matrix shape constraints

    In-place transpose by swapping only works for square matrices because indices map symmetrically.
  2. Step 2: For non-square matrices, in-place transpose is not possible

    Because the shape changes from m x n to n x m, a new matrix must be created to hold the transposed data.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Non-square matrix transpose requires extra space due to dimension change [OK]
Hint: In-place transpose only works for square matrices [OK]
Common Mistakes:
  • Trying to swap elements in-place for non-square matrices
  • Assuming upper triangle swaps apply to rectangular matrices
  • Ignoring dimension changes after transpose
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard