KatInterview

898. Transpose Matrix

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the transpose of a given 2D integer array, matrix. The transpose of a matrix is a new matrix where the rows of the original matrix become the columns, and the columns become the rows.

Solution

Transpose Matrix in Python

class Solution:
    def transpose(self, matrix: list[list[int]]) -> list[list[int]]:
        # Get the dimensions of the input matrix.
        m = len(matrix)
        # The constraints state m >= 1, so no need for an empty check.
        if m == 0:
            return []
        n = len(matrix[0])

        # The transposed matrix will have dimensions n x m.
        # Initialize the result matrix with n rows and m columns.
        result = [[0] * m for _ in range(n)]

        # Iterate through each element of the original matrix.
        for i in range(m):
            for j in range(n):
                # The element at matrix[i][j] moves to result[j][i].
                result[j][i] = matrix[i][j]

        return result

        # A more Pythonic way using zip:
        # *matrix unpacks the rows of the matrix for zip.
        # zip aggregates elements from each row into tuples, forming columns.
        # map(list, ...) converts these tuples into lists.
        # return list(map(list, zip(*matrix)))

Transpose Matrix in Java

class Solution {
    public int[][] transpose(int[][] matrix) {
        // Get the dimensions of the input matrix.
        int m = matrix.length;
        // The constraints state m >= 1, so no need for an empty check,
        // but it's good practice.
        if (m == 0) {
            return new int[0][0];
        }
        int n = matrix[0].length;

        // The transposed matrix will have dimensions n x m.
        // Initialize the result matrix with n rows and m columns.
        int[][] result = new int[n][m];

        // Iterate through each element of the original matrix.
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // The element at matrix[i][j] moves to result[j][i].
                result[j][i] = matrix[i][j];
            }
        }

        return result;
    }
}

Transpose Matrix in C++

class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& matrix) {
        // Get the dimensions of the input matrix.
        int m = matrix.size();
        // The constraints state m >= 1, so no need for an empty check,
        // but it's good practice.
        if (m == 0) {
            return {};
        }
        int n = matrix[0].size();

        // The transposed matrix will have dimensions n x m.
        // Initialize the result matrix with n rows and m columns.
        vector<vector<int>> result(n, vector<int>(m));

        // Iterate through each element of the original matrix.
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                // The element at matrix[i][j] moves to result[j][i].
                result[j][i] = matrix[i][j];
            }
        }

        return result;
    }
};

Transpose Matrix in TypeScript

function transpose(matrix: number[][]): number[][] {
    // Get the dimensions of the input matrix.
    const m = matrix.length;
    // The constraints state m >= 1, so no need for an empty check.
    if (m === 0) {
        return [];
    }
    const n = matrix[0].length;

    // The transposed matrix will have dimensions n x m.
    // Initialize the result matrix with n rows and m columns.
    const result: number[][] = Array(n).fill(0).map(() => Array(m).fill(0));

    // Iterate through each element of the original matrix.
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            // The element at matrix[i][j] moves to result[j][i].
            result[j][i] = matrix[i][j];
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.