Skip to content

Commit a954dd3

Browse files
committed
Runtime: 167 ms (Top 85.71%) | Memory: 73.90 MB (Top 15.71%)
1 parent 2258323 commit a954dd3

File tree

1 file changed

+19
-38
lines changed

1 file changed

+19
-38
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,24 @@
1-
var visibleToRight = function(heights){
2-
const result = new Array(heights.length).fill(0)
1+
// Runtime: 167 ms (Top 85.71%) | Memory: 73.90 MB (Top 15.71%)
2+
3+
/**
4+
* @param {number[]} heights
5+
* @return {number[]}
6+
*/
7+
var canSeePersonsCount = function(heights) {
38
const stack = []
9+
const answer = new Array(heights.length).fill(0)
10+
11+
for(let i = 0; i < heights.length; i++) {
12+
while(stack.length && heights[i] > heights[stack[stack.length - 1]]) {
13+
answer[stack.pop()]++
14+
}
415

5-
let i = heights.length-1
6-
7-
// loop from right to left
8-
while(i >= 0){
9-
let popCount = 0
10-
11-
// Keep Popping untill top ele is smaller
12-
while(stack.length > 0 && stack[stack.length-1][0] < heights[i]){
13-
stack.pop()
14-
popCount+=1
16+
if(stack.length) {
17+
answer[stack[stack.length - 1]]++
1518
}
16-
17-
/////////////////////
18-
/// After Popping ///
19-
////////////////////
20-
21-
// Case1: if ALL elements got popped
22-
if(stack.length === 0)
23-
result[i] = popCount // mark
24-
25-
// Case2: if NO elements were popped
26-
else if(popCount === 0)
27-
result[i] = 1 // mark
28-
29-
// Case3: if SOME elements were popped
30-
else
31-
result[i] = popCount+1 // mark
32-
33-
// store
34-
stack.push([heights[i],popCount])
35-
36-
i-=1
19+
20+
stack.push(i)
3721
}
38-
39-
return result
40-
}
41-
var canSeePersonsCount = function(heights) {
42-
return visibleToRight(heights)
22+
23+
return answer
4324
};

0 commit comments

Comments
 (0)