This question might not be as hard as it looks. We can solve this question by looking at the array from the end, since the question stated "the ocean is right at the buildings".
Looping from the end of the array, we need a variable to keep track of the tallest value, if the value is taller than the tallest gets into the result array.
Time complexity should be O(n).
Link: Buildings With an Ocean View
/**
* @param {number[]} heights
* @return {number[]}
*/
var findBuildings = function(heights) {
let indices = [];
let tallest = 0;
// Edge case
// If there's only 1 element
if(heights.length == 1) return [0];
// Start from the right most (end of array)
// If i is more than previous value, put into the indices
for(let i = heights.length-1; i>=0 ; i--){
if(heights[i] > tallest){
tallest = heights[i];
indices.push(i);
}
}
// Javascript original sort fuction sorts alphabetically
// So we need to overwrite it
indices.sort(function(a, b) {
return a - b;
});
return indices;
};