File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -52,6 +52,7 @@ Happy to accept any contributions to this in any langugage.
52
52
17 . [ Leet Code 554 Brick Wall] ( https://leetcode.com/problems/brick-wall/ ) | [ Solution 1] ( ./level_medium/LeetCode_554_Brick_Wall_Medium.ts )
53
53
18 . [ Leet Code 1190 Reverse Substrings Between Each Pair of Paranthesis] ( https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ ) | [ Solution 1] ( level_medium/LeetCode_1190_Reverse_Substrings.ts ) | [ Solution Optimized] ( level_medium/LeetCode_1190_Reverse_Substrings_1.ts )
54
54
19 . [ Leet Code 22 Generate Paranthesis] ( https://leetcode.com/problems/generate-parentheses/ ) | [ Solution Brute Force] ( level_medium/LeetCode_22_Generate_Paranthesis_1.ts ) | [ Solution BF Optimized] ( level_medium/LeetCode_22_Generate_Paranthesis_2.ts )
55
+ 20 . [ Leet Code 54 Spiral Matrix] | [ Solution] ( ./med/../level_medium/SpiralMatrix.ts )
55
56
56
57
57
58
## Hard
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Problem: LeetCode 54
3
+ * Solution: Uses Multiple pointer approach. Marks the boundaries of the entire array using a row boundary marker
4
+ * and the col boundary markers. Continue to iterate the matrix at the boundary conditions. Keep moving and squeezing
5
+ * the boundary conditions inwards.
6
+ *
7
+ * Complexity: Time O(n) since all the elements are traversed exactly once. Space: O(n) since all the elements
8
+ * are stored once.
9
+ *
10
+ * @param matrix
11
+ */
12
+ function spiralOrder ( matrix : number [ ] [ ] ) : number [ ] {
13
+
14
+ if ( matrix . length === 0 || matrix [ 0 ] . length === 0 ) return [ ]
15
+
16
+ let rowEnd = matrix . length - 1 , rowBeg = 0 ;
17
+ let colEnd = matrix [ 0 ] . length - 1 , colBeg = 0 ;
18
+
19
+ const result : number [ ] = [ ]
20
+
21
+ // Continue till the bounds are within the range.
22
+ while ( rowEnd >= rowBeg && colEnd >= colBeg ) {
23
+ // Add values from horizontal top
24
+ for ( let col = colBeg ; col <= colEnd ; col ++ ) result . push ( matrix [ rowBeg ] [ col ] )
25
+
26
+ // Add values from vertical right
27
+ for ( let row = rowBeg + 1 ; row <= rowEnd ; row ++ ) result . push ( matrix [ row ] [ colEnd ] )
28
+
29
+ // Add values from horizontal bottom
30
+ if ( rowBeg !== rowEnd )
31
+ for ( let col = colEnd - 1 ; col >= colBeg ; col -- ) result . push ( matrix [ rowEnd ] [ col ] )
32
+
33
+ // Add values from vertical left
34
+ if ( colBeg !== colEnd )
35
+ for ( let row = rowEnd - 1 ; row > rowBeg ; row -- ) result . push ( matrix [ row ] [ colBeg ] )
36
+
37
+ // Squeeze
38
+ rowEnd -- ; rowBeg ++ ; colEnd -- ; colBeg ++ ;
39
+ }
40
+
41
+ return result ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments