Skip to content

1762. Buildings With an Ocean View 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> findBuildings(vector<int>& heights) {
    vector<int> stack;

    for (int i = 0; i < heights.size(); ++i) {
      while (!stack.empty() && heights[stack.back()] <= heights[i])
        stack.pop_back();
      stack.push_back(i);
    }

    return stack;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int[] findBuildings(int[] heights) {
    Deque<Integer> stack = new ArrayDeque<>();

    for (int i = 0; i < heights.length; ++i) {
      while (!stack.isEmpty() && heights[stack.peek()] <= heights[i])
        stack.pop();
      stack.push(i);
    }

    int[] ans = new int[stack.size()];
    for (int i = 0; i < ans.length; ++i)
      ans[ans.length - 1 - i] = stack.pop();
    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def findBuildings(self, heights: List[int]) -> List[int]:
    stack = []

    for i, height in enumerate(heights):
      while stack and heights[stack[-1]] <= height:
        stack.pop()
      stack.append(i)

    return stack