| 3 | // time O(n) where n is the number of buildings |
| 4 | // space O(n) |
| 5 | function sunsetViews(buildings, direction) { |
| 6 | let currentMaxHeight = 0; |
| 7 | const stack = []; |
| 8 | |
| 9 | let currentIdx = direction === "EAST" ? buildings.length - 1 : 0; |
| 10 | const step = direction === "EAST" ? -1 : 1; |
| 11 | |
| 12 | while (currentIdx >= 0 && currentIdx < buildings.length) { |
| 13 | let buildingHeight = buildings[currentIdx]; |
| 14 | if (buildingHeight > currentMaxHeight) { |
| 15 | stack.push(currentIdx); |
| 16 | currentMaxHeight = buildingHeight; |
| 17 | } |
| 18 | currentIdx += step; |
| 19 | } |
| 20 | if (direction === "EAST") return stack.reverse(); // time O(n) |
| 21 | return stack; |
| 22 | } |
| 23 | |
| 24 | const buildings = [3, 5, 4, 4, 3, 1, 3, 2]; |
| 25 | const direction = "EAST"; |