Cyclically Rotating a Grid LeetCode solution in JavaScript

1
var rotateGrid = function (grid, k) {
2
const m = grid.length;
3
const n = grid[0].length;
4

5
let startRow = 0;
6
let endRow = m - 1;
7

8
let startCol = 0;
9
let endCol = n - 1;
10

11
while (startRow <= endRow && startCol <= endCol) {
12
let currRowStart = startRow;
13
let currRowEnd = endRow;
14

15
let currColStart = startCol;
16
let currColEnd = endCol;
17

18
const vals = [];
19

20
// Top
21
for (let col = currColStart; col <= currColEnd; ++col) {
22
const val = grid[currRowStart][col];
23
vals.push(val);
24
}
25
++currRowStart;
26

27
// Right
28
for (let row = currRowStart; row <= currRowEnd; ++row) {
29
const val = grid[row][currColEnd];
30
vals.push(val);
31
}
32
--currColEnd;
33

34
// Bottom
35
for (let col = currColEnd; col >= currColStart; --col) {
36
const val = grid[currRowEnd][col];
37
vals.push(val);
38
}
39
--currRowEnd;
40

41
// Left
42
for (let row = currRowEnd; row >= currRowStart; --row) {
43
const val = grid[row][currColStart];
44
vals.push(val);
45
}
46
++currColStart;
47

48
const size = vals.length;
49
const remK = k % size;
50

51
const movedVals = [];
52

53
for (let i = 0; i < size; ++i) {
54
const movedIdx = (i + remK) % size;
55
movedVals[i] = vals[movedIdx];
56
}
57

58
let i = 0;
59

60
currRowStart = startRow;
61
currRowEnd = endRow;
62

63
currColStart = startCol;
64
currColEnd = endCol;
65

66
// Top
67
for (let col = currColStart; col <= currColEnd; ++col) {
68
grid[currRowStart][col] = movedVals[i++];
69
}
70
++currRowStart;
71

72
// Right
73
for (let row = currRowStart; row <= currRowEnd; ++row) {
74
grid[row][currColEnd] = movedVals[i++];
75
}
76
--currColEnd;
77

78
// Bottom
79
for (let col = currColEnd; col >= currColStart; --col) {
80
grid[currRowEnd][col] = movedVals[i++];
81
}
82
--currRowEnd;
83

84
// Left
85
for (let row = currRowEnd; row >= currRowStart; --row) {
86
grid[row][currColStart] = movedVals[i++];
87
}
88
++currColStart;
89

90
// update the boundaries for the next layer
91
startRow = currRowStart;
92
endRow = currRowEnd;
93

94
startCol = currColStart;
95
endCol = currColEnd;
96
}
97

98
return grid;
99
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0