Transpose Matrix — Leetcode 867 (Ruby Solution)

  • Post last modified:December 11, 2023
  • Reading time:2 mins read

Ruby’s solution for finding the transpose of a matrix

Introduction

A transpose of a matrix is a new matrix formed by exchanging rows with columns. In this leetcode problem, we will find the transpose of a matrix.

Problem

Given a 2D integer array matrix, return the transpose of matrix.

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

Example 1:

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

Example 2:

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

Solution

  • If the input matrix is of size ROW, COL then the Transpose matrix would be of size of ROW=COL & COL=ROW.
  • The location of elements in the transpose matrix will be inverted as well, which means if the element in the input matrix is at i, j then in the transpose matrix it would be j, i.
    so, transpose[col][row]=matrix[row][col]
# @param {Integer[][]} matrix
# @return {Integer[][]}
def transpose(matrix)
    rows = matrix.size
    cols = matrix[0].size
    res = Array.new(cols) { Array.new(rows) }
    matrix.each_with_index do |row, i|
      row.each_with_index do |val, j| 
        res[j][i] = val
      end
    end
    res
end

Results

  • Our solution is accepted and it’s pretty efficient.

Complexity

Time complexity:
time complexity is O(N²) since we are iterating over each element.

Space complexity:
space complexity is O(N), and N is the size of the input matrix for the result matrix.

Conclusion

In this problem, we learned about the 2D matrix and the transpose of a matrix. Time complexity is O(N²) and space complexity is O(N) where N is space of original matrix.

Before You Leave