File tree 1 file changed +12
-12
lines changed
scripts/algorithms/N/Number of Visible People in a Queue
1 file changed +12
-12
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 354 ms (Top 65.08%) | Memory: 83 MB (Top 6.35%)
1
2
var visibleToRight = function ( heights ) {
2
3
const result = new Array ( heights . length ) . fill ( 0 )
3
4
const stack = [ ]
4
5
5
6
let i = heights . length - 1
6
-
7
+
7
8
// loop from right to left
8
- while ( i >= 0 ) {
9
+ while ( i >= 0 ) {
9
10
let popCount = 0
10
-
11
+
11
12
// Keep Popping untill top ele is smaller
12
13
while ( stack . length > 0 && stack [ stack . length - 1 ] [ 0 ] < heights [ i ] ) {
13
- stack . pop ( )
14
+ stack . pop ( )
14
15
popCount += 1
15
16
}
16
-
17
+
17
18
/////////////////////
18
19
/// After Popping ///
19
20
////////////////////
20
-
21
+
21
22
// Case1: if ALL elements got popped
22
23
if ( stack . length === 0 )
23
24
result [ i ] = popCount // mark
24
-
25
+
25
26
// Case2: if NO elements were popped
26
27
else if ( popCount === 0 )
27
28
result [ i ] = 1 // mark
28
-
29
+
29
30
// Case3: if SOME elements were popped
30
31
else
31
32
result [ i ] = popCount + 1 // mark
32
-
33
+
33
34
// store
34
35
stack . push ( [ heights [ i ] , popCount ] )
35
-
36
+
36
37
i -= 1
37
38
}
38
-
39
+
39
40
return result
40
41
}
41
42
var canSeePersonsCount = function ( heights ) {
42
43
return visibleToRight ( heights )
43
44
} ;
44
-
You can’t perform that action at this time.
0 commit comments