-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04.transposeMatrix.js
50 lines (39 loc) · 943 Bytes
/
04.transposeMatrix.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Write a function
// that returns the transpose of the matrix.
// The transpose of a matrix is a flipped version of the original matrix across
// its main diagonal (which runs from top-left to bottom-right); it switches
// the row and column indices of the original matrix.
// https://www.algoexpert.io/questions/transpose-matrix
// looking in to this
function transposeMatrix(input) {
// Time complexity: O(w * h)
//
// Space complexity: O(w * h)
//
let answer = []
let i = 0;
let j = 0;
let columnCount = input[i].length // i.e. 3
let transposedRow = []
while (j < columnCount) {
for (let i = 0; i < input.length; i++) {
transposedRow.push(input[i][j])
}
j++;
answer.push(transposedRow);
transposedRow = [];
}
return answer;
}
let input = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
input = [
[1, 2],
[3, 4],
[5, 6]
];
let answer = transposeMatrix(input)
console.log(answer)