Buildings With an Ocean View

MediumStackmonotonic stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n buildings in a line with heights heights[0..n-1], and the ocean lies to the right of the last building. A building has an ocean view if every building to its right is strictly shorter than it. Return the indices (0-based) of all buildings with an ocean view, sorted in increasing order. Aim for O(n) time.

Examples

Input: heights = [5,2,4,3,1]
Output: [0,2,3,4]
Building 1 (height 2) is blocked by the building of height 4; every other building sees the ocean.
Input: heights = [2,2,2]
Output: [2]
An equal-height building blocks the view, so only the last one qualifies.

Constraints

  • 1 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic stack problems