A row of buildings stands along a street that runs west to east, and the sea is at the east end, to the right of the last building. A building has a sea view when it is strictly taller than every building to its right; the easternmost building always has one.
heights is an array of non-negative finite numbers: heights[i] is the height of building i, numbered from west (0) to east.
Write:
seaViewBuildings(heights): returns the indexes of all buildings with a sea view, in ascending order. An empty street returns [].
class SeaViewSkyline: a developer keeps adding new buildings at the east end of the street, between the current last building and the sea.
add(height) adds the next building (its index is the number of buildings added before it) and returns how many buildings have a sea view now.
viewIndexes() returns the indexes of the buildings that currently have a sea view, in ascending order, as a new array.
Rules:
A building of equal height to the right blocks the view.
Throw a TypeError if heights is not an array, or if a height is not a non-negative finite number (also in add).
Streets can have 200,000 buildings, and the tests call add 200,000 times, reading the count after each. Rechecking the whole street on each call, or comparing every pair of buildings, is far too slow.
seaViewBuildings([4, 2, 3, 1]); // [0, 2, 3]: building 1 is hidden by building 2seaViewBuildings([2, 2, 2]); // [2]: equal heights block the viewseaViewBuildings([1, 2, 3]); // [2]const skyline = new SeaViewSkyline();skyline.add(5); // 1skyline.add(3); // 2skyline.add(4); // 2: the 3 loses its viewskyline.viewIndexes(); // [0, 2]skyline.add(9); // 1
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.