Buildings With an Ocean View

Picture a row of buildings facing the ocean on the right. A building sees the ocean only if nothing taller blocks it. The interviewer wants to see if you can answer this in one pass instead of checking each building against all the others. That one-pass idea is the test.

🎯 The Problem

You get a row of building heights. The ocean is to the right. Return the buildings that can see it.

  • Each number is one building’s height. They stand in a row.
  • The ocean sits to the right of the last building.
  • A building sees the ocean if every building to its right is shorter than it.
  • Return the positions of all buildings that can see the ocean.
  • The positions must read left to right.
  • The tallest building seen so far on the right is the running max.

Say the heights are [4, 2, 3, 1]. The last building always sees the ocean. The 3 sees over the 1. The 4 sees over everyone. The 2 is blocked by the 3. So the answer is positions 0, 2, and 3.

Input: heights = [4, 2, 3, 1]
Output: [0, 2, 3]
Explanation:
index 3 (height 1): nothing to its right, sees ocean
index 2 (height 3): only a 1 to the right, sees ocean
index 1 (height 2): a 3 to the right blocks it, no view
index 0 (height 4): tallest of all, sees ocean

Here is the row of buildings with the ocean on the right.

index 0 height 4

index 1 height 2

index 2 height 3

index 3 height 1

ocean

🐒 Approach 1: Check Everything on the Right (Brute Force)

The idea in one line: for each building, scan all buildings to its right.

The idea:

  • Take one building.
  • Look at every building to its right.
  • If all of them are shorter, this one sees the ocean.

How it works:

  • One loop picks a building.
  • A second loop scans to its right.
  • Find any building taller or equal, and this one is blocked.
  • Reach the end with nothing blocking, and it sees the ocean.

Why it is weak:

  • For each building you scan the rest of the row.
  • That is O(nΒ²) work.
  • A long row makes this slow.

Here is the brute-force code for that idea:

buildings_with_ocean_view_brute_force.py
def find_buildings(heights):
answer = []
for i in range(len(heights)):
blocked = False
for j in range(i + 1, len(heights)):
if heights[j] >= heights[i]:
blocked = True
break
if not blocked:
answer.append(i)
return answer
print(find_buildings([4, 2, 3, 1]))

⚑ Approach 2: Scan Right to Left With a Running Max (Best)

The idea in one line: walk from the right and carry the tallest height seen so far.

The idea:

  • A building sees the ocean only if it beats everything to its right.
  • So the only thing that matters is the tallest building on the right.
  • Carry that tallest height in one number as you walk backward.

How it works:

  • Start a running max lower than any real height.
  • Walk from the last building back to the first.
  • At each building, ask: is it taller than the running max?
  • If yes, nothing to its right is as tall, so record its position. Then update the running max.
  • If no, something taller blocks it, so skip it.
  • The positions come out right to left, so reverse the list at the end.

Why it is fast:

  • One backward walk touches each building once. That is O(n).
  • You carry a single number instead of rescanning the row.

Here is the dry run on [4, 2, 3, 1]. The running max starts very low.

running max = -1, scan right to left

index 3 height 1 > -1, sees ocean, max = 1

index 2 height 3 > 1, sees ocean, max = 3

index 1 height 2 < 3, blocked

index 0 height 4 > 3, sees ocean, max = 4

collected 3,2,0 then reversed to 0,2,3

Steps to Solve

  1. Start a running max set lower than any height.
  2. Walk the heights from the last index back to the first.
  3. At each building, if its height is greater than the running max, it sees the ocean. Record its index.
  4. Update the running max to this building’s height when it sees the ocean.
  5. Reverse the collected indices so they read left to right.

This Python version collects indices in a list while scanning right, then reverses it.

ocean_view.py
def find_buildings(heights):
result = []
running_max = -1 # lower than any height
for i in range(len(heights) - 1, -1, -1): # scan right to left
if heights[i] > running_max: # taller than all on right
result.append(i) # this building sees the ocean
running_max = heights[i] # update the tallest seen
result.reverse() # put indices in left-to-right order
return result
heights = [4, 2, 3, 1]
print(find_buildings(heights))

The output of the above code will be:

[0, 2, 3]

Let us walk through the Python version line by line. The line running_max = -1 sets the tallest height seen so far. We start below any real height so the very first building on the right always counts. The last building has nothing to its right, so it always sees the ocean.

The loop for i in range(len(heights) - 1, -1, -1) walks from the last index back to 0. We scan right to left because the ocean is on the right. The tallest blocker for any building is whatever stands to its right, and that is what we have already passed.

The check if heights[i] > running_max is the heart of it. If the current building is taller than everything to its right, nothing blocks it. So we result.append(i) to record its position. Then running_max = heights[i] updates the tallest seen, since this building now stands between the ocean and anything further left.

The line result.reverse() flips the list. We collected the indices from right to left, so they came out as [3, 2, 0]. Reversing gives [0, 2, 3], the order the problem asks for.

⏱️ Time and Space Complexity

The brute force checks each building against all buildings on its right, so it is O(nΒ²). The running max scan walks the array one time and updates a single number, so it is O(n). We store only the answer list, which holds at most every index once, so the extra space is O(n) for the output, or O(1) if you do not count the output.

Approach Time Complexity Space Complexity
Brute force (look at all on right) O(nΒ²) O(1)
Right-to-left running max O(n) O(1) extra

Tip

The insight to say out loud is that scanning from the right lets one running max answer every building at once. Naming that single carried value shows the interviewer you found the O(n) pass.

🧩 Key Takeaways

  • βœ… A building sees the ocean only if it is taller than every building to its right.
  • βœ… Scan from right to left so the tallest blocker is always behind you.
  • βœ… Carry one running max instead of rescanning the row each time.
  • βœ… Record an index only when the building beats the running max, then update it.
  • βœ… Reverse the collected indices at the end for left-to-right order.

Check Your Knowledge

4 questions Show quiz Hide quiz

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    When does a building have an ocean view?

    Why: A building sees the ocean if all buildings to its right are strictly shorter.

  2. 2

    Why do we scan from right to left?

    Why: Scanning right to left lets a single running max track the tallest blocker seen so far.

  3. 3

    What do we do when a building's height beats the running max?

    Why: If it is taller than all on its right, it sees the ocean, so we record it and raise the running max.

  4. 4

    Why do we reverse the result list at the end?

    Why: The scan gathers indices in right-to-left order, so reversing gives the required left-to-right order.

πŸš€ What’s Next?