LeetCode 867: Transpose Matrix Solution

Master LeetCode problem 867 (Transpose Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

867. Transpose Matrix

Problem Explanation

Explanation

To transpose a matrix, we need to flip the matrix over its main diagonal, which means swapping the rows and columns. We can achieve this by iterating through the original matrix and constructing a new transposed matrix. The transposed matrix will have the number of rows equal to the number of columns of the original matrix and vice versa.

  • Algorithm:

    1. Initialize a new 2D array to store the transposed matrix with dimensions n x m.
    2. Iterate through each element of the original matrix.
    3. Place the element at position (i, j) in the original matrix to position (j, i) in the transposed matrix.
    4. Return the transposed matrix.
  • Time Complexity: O(m * n) where m and n are the dimensions of the original matrix.

  • Space Complexity: O(m * n) for the transposed matrix.

Solution Code

class Solution {
    public int[][] transpose(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        
        int[][] transposed = new int[n][m];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                transposed[j][i] = matrix[i][j];
            }
        }
        
        return transposed;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 867 (Transpose Matrix)?

This page provides optimized solutions for LeetCode problem 867 (Transpose Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 867 (Transpose Matrix)?

The time complexity for LeetCode 867 (Transpose Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 867 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 867 in Java, C++, or Python.

Back to LeetCode Solutions