MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / sunsetViews

Function sunsetViews

stacks/sunset-views.js:5–22  ·  view source on GitHub ↗
(buildings, direction)

Source from the content-addressed store, hash-verified

3// time O(n) where n is the number of buildings
4// space O(n)
5function 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";

Callers 1

sunset-views.jsFile · 0.85

Calls 1

pushMethod · 0.45

Tested by

no test coverage detected