Buildings With an Ocean View solution explained
Buildings With an Ocean View gives a row of building heights with the ocean to the right and asks which buildings can see it: a building can if every building to its right is strictly shorter. Scan from right to left while tracking the tallest height seen so far; a building is visible exactly when it is taller than that maximum. That is one O(n) pass with O(1) extra space besides the answer.
By Evin JohnPublished 7 min read
The task, restated
You get a list of building heights from west to east, and the ocean lies just east of the last building. A building has an ocean view if nothing between it and the ocean is as tall as it or taller. Return the indexes of all such buildings in increasing order. Heights are positive integers. The last building always has a view, since nothing stands between it and the water.
| Heights | Answer | Why |
|---|---|---|
| [4, 2, 3, 1] | [0, 2, 3] | Index 1 (height 2) is blocked by the 3 to its right |
| [1, 3, 2, 4] | [3] | The 4 at the end blocks everything |
| [5, 4, 3, 2, 1] | [0, 1, 2, 3, 4] | Strictly decreasing, so every building sees the ocean |
| [2, 2, 2] | [2] | Equal height blocks the view, so only the last one counts |
| [7] | [0] | A single building |
Ask about ties before coding. In the usual version a building of equal height blocks the view, which is why [2, 2, 2] has one answer. If the interviewer says equal heights do not block, the comparison changes from greater-than to greater-than-or-equal, and nothing else does.
Why it is asked
It is a warm-up that checks one habit: noticing that the condition depends only on what is to the right, so you should walk from the right. Candidates who scan left to right end up either re-checking the suffix for every building or reaching for a stack before they need one. Follow-ups tend to move the ocean or the input:
- Ocean on the left. Scan left to right with the same running maximum; no reversal needed.
- Ocean on both sides. A building qualifies if it beats the maximum on its left or the maximum on its right; compute both with two passes.
- Heights arrive one at a time from the west. You cannot look ahead, so keep a stack of candidates and pop any that the new building blocks.
- Count, for each building, how many it can see to the east. That is a different problem solved with a monotonic stack and counting pops.
Brute force: check every suffix
For each index, look at every building to its right and confirm they are all shorter. This is the definition turned directly into code. It is O(n²) in the worst case, for example on a strictly decreasing row where every check has to run to the end. It makes a solid reference for testing.
def ocean_view_slow(heights):
seen = []
for i, h in enumerate(heights):
if all(other < h for other in heights[i + 1:]):
seen.append(i)
return seenOptimal approach: scan from the right
The tallest building to the right of index i is all that matters for i, and that value can be updated in O(1) as you move left. Start with tallest = 0, since heights are positive. Walk from the last index to the first. If the current height is greater than tallest, record the index. Then set tallest to the larger of the two. The recorded indexes come out in decreasing order, so reverse them before returning.
def ocean_view(heights):
seen = []
tallest = 0
for i in range(len(heights) - 1, -1, -1):
if heights[i] > tallest:
seen.append(i)
tallest = heights[i]
seen.reverse()
return seenfunction oceanView(heights) {
const seen = [];
let tallest = 0;
for (let i = heights.length - 1; i >= 0; i--) {
if (heights[i] > tallest) {
seen.push(i);
tallest = heights[i];
}
}
return seen.reverse();
}Updating tallest only inside the if is enough, because a building that is not taller than tallest cannot raise it. Starting tallest at 0 relies on heights being positive; if zero-height or negative values were possible, start at negative infinity instead.
Trace: [4, 2, 3, 1]
| Index | Height | Tallest to the right | Visible? | Recorded so far |
|---|---|---|---|---|
| 3 | 1 | 0 | yes | [3] |
| 2 | 3 | 1 | yes | [3, 2] |
| 1 | 2 | 3 | no | [3, 2] |
| 0 | 4 | 3 | yes | [3, 2, 0] |
| reverse | [0, 2, 3] |
Follow-up: heights arrive from the west
If you must process buildings left to right, keep a stack of indexes that can still see the ocean given everything seen so far. When a new building arrives, any building on the stack that is not taller than it has just lost its view, so pop it. Then push the new building, which can see the ocean for now. The stack is always strictly decreasing in height from bottom to top, and at the end it holds the answer in increasing index order. Each index is pushed and popped at most once, so the total is O(n), with O(n) space for the stack.
def ocean_view_streaming(heights):
stack = []
for i, h in enumerate(heights):
while stack and heights[stack[-1]] <= h:
stack.pop()
stack.append(i)
return stackTime and space
| Approach | Time | Extra space |
|---|---|---|
| Check every suffix | O(n²) | O(1) besides the answer, O(n) with Python slicing |
| Right-to-left running maximum | O(n) | O(1) besides the answer |
| Left-to-right monotonic stack | O(n) amortized | O(n) for the stack |
Edge cases
- An empty list returns an empty list.
- A single building returns [0].
- All equal heights return only the last index.
- A strictly increasing row returns only the last index.
- A strictly decreasing row returns every index, the worst case for the brute force.
Mistakes to avoid
- Using greater-than-or-equal when ties should block, or the reverse, without asking.
- Forgetting to reverse the result of the right-to-left scan.
- Inserting at the front of a list to avoid the reversal, which is O(n) per insert in Python and JavaScript arrays.
- Scanning left to right and recomputing the suffix maximum for each building.
- In the stack version, popping with a strict comparison, which leaves an equal-height building on the stack as if it could still see.
How to explain it out loud
Fictional example
- Candidate
- Whether a building sees the ocean depends only on the buildings to its right, so I'll walk from the right and keep the tallest height so far.
- Candidate
- A building is visible if it's strictly taller than that maximum. I record it and update the maximum, then reverse the list at the end so the indexes are increasing.
- Candidate
- One pass, linear time, constant space besides the output. If the heights had to be processed from the left as a stream, I'd use a decreasing stack instead.
Related problems
Valid Palindrome II is another single-scan problem where the trick is deciding what to compare at each step. Design Browser History is a quick design question that pairs well with this one in a short practice set. Valid Parentheses is the simplest stack problem, if the monotonic stack follow-up felt new.
How Natively can help you practice
Natively works on Mac and Windows. During practice it can read a warm-up like this from a screenshot or from the browser through its Chrome extension and write an approach with code, so you can compare it with your own in seconds and move on. It also saves a transcript of each session, which is useful for checking that you asked about ties before coding. See the AI interview assistant page.
Questions people ask
How do you solve Buildings With an Ocean View?
Scan the heights from right to left while tracking the tallest building seen so far. A building has a view exactly when it is strictly taller than that maximum. Record those indexes, then reverse the list so they come out in increasing order.
What is the time complexity of Buildings With an Ocean View?
The right-to-left scan is O(n) time with O(1) extra space besides the answer. Checking every suffix for each building is O(n²), and a left-to-right monotonic stack is O(n) amortized with O(n) space for the stack.
Does a building of equal height block the ocean view?
In the usual version it does, so [2, 2, 2] has only the last index as an answer. Ask before coding: if equal heights do not block, only the comparison changes from greater-than to greater-than-or-equal.
What if the heights arrive one at a time from the west?
Keep a stack of indexes that can still see the ocean. When a new building arrives, pop every building on the stack that is not taller than it, then push the new one. At the end the stack holds the answer in increasing order.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
