We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Transpose Matrix

Number: 898

Difficulty: Easy

Paid? No

Companies: Google, Verkada, Amazon, Microsoft, Apple, Bloomberg, Adobe


Problem Description

Given a 2D integer array matrix, return the transpose of matrix. The transpose is obtained by flipping the matrix over its main diagonal, thereby switching the matrix's row and column indices.


Key Insights

  • The value at position (i, j) in the original matrix moves to (j, i) in the transposed matrix.
  • The transposed matrix dimensions are the reverse of the original: if the original is m x n, then the transposed is n x m.
  • A simple double loop is sufficient to swap the indices, ensuring O(m*n) time complexity.
  • This problem handles both square and rectangular matrices.

Space and Time Complexity

Time Complexity: O(mn)
Space Complexity: O(m
n) for the new matrix holding the transposed values


Solution

The solution involves iterating over each element of the original matrix and assigning it to the corresponding position in the new matrix where the indexes are swapped. We create the transposed matrix with dimensions based on the number of columns and rows of the original matrix, respectively. The approach leverages basic array manipulation with nested loops to fill in the new matrix.


Code Solutions

# Python solution with clear comments

def transpose(matrix):
    # Number of rows in the original matrix
    num_rows = len(matrix)
    # Number of columns in the original matrix
    num_cols = len(matrix[0])
    
    # Create a new matrix with dimensions swapped: num_cols x num_rows
    transposed = [[0] * num_rows for _ in range(num_cols)]
    
    # Iterate through each element in the original matrix
    for i in range(num_rows):
        for j in range(num_cols):
            # Place the element at the swapped index in the transposed matrix
            transposed[j][i] = matrix[i][j]
    
    return transposed

# Example usage:
matrix = [[1, 2, 3], [4, 5, 6]]
print(transpose(matrix))
← Back to All Questions