File tree Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ var setZeroes = function ( matrix ) {
2
+ let rows = new Set ( ) ;
3
+ let cols = new Set ( ) ;
4
+
5
+ for ( let row = 0 ; row < matrix . length ; row ++ ) {
6
+ for ( let col = 0 ; col < matrix [ 0 ] . length ; col ++ ) {
7
+ if ( matrix [ row ] [ col ] === 0 ) {
8
+ rows . add ( row ) ;
9
+ cols . add ( col ) ;
10
+ }
11
+ }
12
+ }
13
+
14
+ for ( let row = 0 ; row < matrix . length ; row ++ ) {
15
+ for ( let col = 0 ; col < matrix [ 0 ] . length ; col ++ ) {
16
+ if ( rows . has ( row ) || cols . has ( col ) ) {
17
+ matrix [ row ] [ col ] = 0 ;
18
+ }
19
+ }
20
+ }
21
+ } ;
22
+
23
+ // TC: O(m*n)
24
+ // SC: O(m+n)
Original file line number Diff line number Diff line change
1
+ var spiralOrder = function ( matrix ) {
2
+ // Edge case
3
+ if ( matrix . length === 0 ) return [ ] ;
4
+
5
+ let result = [ ] ;
6
+ let rowStart = 0 ,
7
+ rowEnd = matrix . length - 1 ;
8
+ let colStart = 0 ,
9
+ colEnd = matrix [ 0 ] . length - 1 ;
10
+
11
+ while ( rowStart <= rowEnd && colStart <= colEnd ) {
12
+ // Traverse right
13
+ for ( let col = colStart ; col <= colEnd ; col ++ ) {
14
+ result . push ( matrix [ rowStart ] [ col ] ) ;
15
+ }
16
+ rowStart ++ ;
17
+
18
+ // Traverse down
19
+ for ( let row = rowStart ; row <= rowEnd ; row ++ ) {
20
+ result . push ( matrix [ row ] [ colEnd ] ) ;
21
+ }
22
+ colEnd -- ;
23
+
24
+ // Traverse left (check if rowStart <= rowEnd to avoid duplicates)
25
+ if ( rowStart <= rowEnd ) {
26
+ for ( let col = colEnd ; col >= colStart ; col -- ) {
27
+ result . push ( matrix [ rowEnd ] [ col ] ) ;
28
+ }
29
+ rowEnd -- ;
30
+ }
31
+
32
+ // Traverse up (check if colStart <= colEnd to avoid duplicates)
33
+ if ( colStart <= colEnd ) {
34
+ for ( let row = rowEnd ; row >= rowStart ; row -- ) {
35
+ result . push ( matrix [ row ] [ colStart ] ) ;
36
+ }
37
+ colStart ++ ;
38
+ }
39
+ }
40
+
41
+ return result ;
42
+ } ;
43
+
44
+ // TC: O(m*n)
45
+ // SC: O(m*n)
Original file line number Diff line number Diff line change
1
+ var getSum = function ( a , b ) {
2
+ while ( b !== 0 ) {
3
+ if ( b > 0 ) {
4
+ a ++ ;
5
+ b -- ;
6
+ } else {
7
+ b ++ ;
8
+ a -- ;
9
+ }
10
+ }
11
+ return a ;
12
+ } ;
13
+
14
+ // |b| is absolute value of b
15
+ // TC: O(|b|)
16
+ // SC: O(1)
You can’t perform that action at this time.
0 commit comments