Similar Problems

Similar Problems not available

Order Two Columns Independently - Leetcode Solution

Companies:

LeetCode:  Order Two Columns Independently Leetcode Solution

Difficulty: Medium

Topics: database  

Problem Statement:

Given a two-dimensional integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the row and column indices of the matrix.

Example:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]

Solution:

The transpose of a matrix can be obtained by swapping the elements of the matrix across the diagonal. For instance, if we have the following matrix:

[[1,2,3], [4,5,6], [7,8,9]]

The transpose of this matrix would be:

[[1,4,7], [2,5,8], [3,6,9]]

To solve this problem, we can use a nested loop to swap the elements across the diagonal. We can start by swapping the element at (0,1) with the element at (1,0), then swap the element at (0,2) with the element at (2,0), and so on until we have swapped all the elements across the diagonal.

Here is the implementation of the solution:

class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: # get the dimensions of the matrix rows = len(matrix) cols = len(matrix[0])

    # create a new matrix with the swapped dimensions
    transpose = [[0 for _ in range(rows)] for _ in range(cols)]
    
    # iterate over the elements of the matrix and swap them
    for i in range(rows):
        for j in range(cols):
            transpose[j][i] = matrix[i][j]
    
    return transpose

The time complexity of this approach is O(mn) since we need to iterate over all the elements of the matrix. The space complexity is also O(mn) since we need to create a new matrix to store the transpose.

Order Two Columns Independently Solution Code

1