forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Visible People in a Queue.js
44 lines (34 loc) · 1.05 KB
/
Number of Visible People in a Queue.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
// Runtime: 354 ms (Top 65.08%) | Memory: 83 MB (Top 6.35%)
var visibleToRight = function(heights){
const result = new Array(heights.length).fill(0)
const stack = []
let i = heights.length-1
// loop from right to left
while(i >= 0){
let popCount = 0
// Keep Popping untill top ele is smaller
while(stack.length > 0 && stack[stack.length-1][0] < heights[i]){
stack.pop()
popCount+=1
}
/////////////////////
/// After Popping ///
////////////////////
// Case1: if ALL elements got popped
if(stack.length === 0)
result[i] = popCount // mark
// Case2: if NO elements were popped
else if(popCount === 0)
result[i] = 1 // mark
// Case3: if SOME elements were popped
else
result[i] = popCount+1 // mark
// store
stack.push([heights[i],popCount])
i-=1
}
return result
}
var canSeePersonsCount = function(heights) {
return visibleToRight(heights)
};