1762. Buildings With an Ocean View

this is a very basic mono stack question

T: O(n)

S: O(n)

class Solution {
    public int[] findBuildings(int[] heights) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < heights.length; i++) {
            while (!stack.isEmpty() && heights[i] >= heights[stack.peek()]) {
                stack.pop();
            }
            stack.push(i);
        }
        int[] result = new int[stack.size()];
        for (int i = stack.size() - 1; i >= 0; i--) {
            result[i] = stack.pop();
        }
        return result;
    }
}

/*
when num > peek,
add to result
pop 

1
3
      2  => pop
4



1
2
3
4



4



3


1
*/

Last updated