← Back to libraryQuestion 104 of 273
⌨️Java CodingIntermediate

Transpose a Matrix

📌 Definition:

Swap the rows and columns of a matrix so element [i][j] moves to [j][i] (an m x n matrix becomes n x m).

📖 Detailed Explanation:

Allocate a result of transposed dimensions and copy each element to its swapped position; for a square matrix you can swap in place across the diagonal. O(m * n) time.

💻 Solutions:
public static int[][] transpose(int[][] m) {
    int rows = m.length, cols = m[0].length;
    int[][] t = new int[cols][rows];
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            t[j][i] = m[i][j];
    return t;
}
function transpose(m) {
  return m[0].map((_, j) => m.map(row => row[j]));
}
def transpose(m):
    return [list(row) for row in zip(*m)]
🔑 Key Points:
  • Element [i][j] -> [j][i]
  • Non-square needs a new n x m result
  • Square can swap in place above the diagonal
  • O(m*n) time
🌍 Real-World Example:

Transposition is a staple of data reshaping (rows-to-columns pivots) and linear-algebra routines used in analytics and graphics.

🎯 Scenario-Based Interview Question:

A candidate swaps in place with two nested loops over the full range and the matrix ends up unchanged. Why?