Buildings With an Ocean View

medium monotonic stack array

Problem

Given building heights left-to-right with the ocean on the right, return indices of buildings whose view to the right is unobstructed (strictly taller than everything after).

Inputheights = [4,2,3,1]
Output[0,2,3]
Building at index 1 (height 2) is blocked by index 2 (height 3).

def find_buildings(heights):
    out = []
    cur_max = 0
    for i in range(len(heights) - 1, -1, -1):
        if heights[i] > cur_max:
            out.append(i)
            cur_max = heights[i]
    out.reverse()
    return out
function findBuildings(heights) {
  const out = [];
  let m = 0;
  for (let i = heights.length - 1; i >= 0; i--) {
    if (heights[i] > m) { out.push(i); m = heights[i]; }
  }
  return out.reverse();
}
class Solution {
    public int[] findBuildings(int[] heights) {
        List<Integer> rev = new ArrayList<>();
        int m = 0;
        for (int i = heights.length - 1; i >= 0; i--) {
            if (heights[i] > m) { rev.add(i); m = heights[i]; }
        }
        Collections.reverse(rev);
        int[] out = new int[rev.size()];
        for (int i = 0; i < out.length; i++) out[i] = rev.get(i);
        return out;
    }
}
vector<int> findBuildings(vector<int>& heights) {
    vector<int> out;
    int m = 0;
    for (int i = (int)heights.size() - 1; i >= 0; i--) {
        if (heights[i] > m) { out.push_back(i); m = heights[i]; }
    }
    reverse(out.begin(), out.end());
    return out;
}
Time: O(n) Space: O(1)