leetcode : 867. Transpose Matrix
This one took a while to get. Originally I was trying to transpose in place, but you cannot guarantee the input is a square, so in place won’t work.Not sure if even in C you can transpose in place for a rectangular input. There maybe some memory tricks there, but they definitely are not available for JavaScript
Code is commented to guide
var transpose = function(A) {
//this problem we actually cant transpose in place
//since we cannot guarantee that the input is a square
const result = []
const rowsLength = A[0].length
const columnsLength = A.length
for(i=0;i<rowsLength;i++){
let column = []
for(j=0;j<columnsLength;j++){
//here we get all elements in a column from input array A
//and add it to new array named column
column.push(A[j][i])
}
//we take the variable column we generated above
//and turn it into a row for output Array result
result.push(column)
}
return result
};