Buildings With an Ocean View

Updated on 20 May, 2025
Buildings With an Ocean View header image

Problem Statement

In this problem, we're presented with a scenario where there are n sequential buildings, each with a distinct height, along a line adjacent to an ocean. The ocean is positioned to the right end of this line of buildings. A building is defined to have an "ocean view" if there are no taller buildings to its right, allowing an unobstructed view of the ocean. Our task is to find out which buildings have such unobstructed views.

We will determine which buildings meet the criteria of an ocean view by examining their heights relative to the buildings to their right. The results are returned as a list of indices, in increasing order, representing the buildings that have an ocean view. The indices are 0-based, meaning that the first building in the sequence is indexed as 0, the second as 1, and so on up to n-1.

Examples

Example 1

Input:

heights = [4,2,3,1]

Output:

[0,2,3]

Explanation:

Building 1 (0-indexed) does not have an ocean view because building 2 is taller.

Example 2

Input:

heights = [4,3,2,1]

Output:

[0,1,2,3]

Explanation:

All the buildings have an ocean view.

Example 3

Input:

heights = [1,3,2,4]

Output:

[3]

Explanation:

Only building 3 has an ocean view.

Constraints

  • 1 <= heights.length <= 105
  • 1 <= heights[i] <= 109

Approach and Intuition

Understanding the problem and constructing an efficient approach can be broken down into the following steps:

  1. Begin evaluating buildings from the rightmost side towards the left. This right-to-left approach allows us to keep track of the tallest building encountered so far and compare each building against this maximum.
  2. Maintain a list where we'll append indices of the buildings which have a view of the ocean.
  3. Initialize a variable, say max_height_so_far, to 0 or the minimum possible height, which will record the height of the tallest building observed as we iterate from right to left.
  4. Iterate through the array of building heights in reverse. For each building, compare its height with max_height_so_far:
    • If the current building's height is greater than max_height_so_far, it means this building has an ocean view. Update max_height_so_far to this new height and add the building's index to our list of ocean-view buildings.
    • If not, simply continue to the next building.
  5. Since the iteration is from right to left, and results need to be in increasing order of their indices, reverse the list of indices collected.
  6. The final list will give the indices of all buildings that have an unobstructed view of the ocean, sorted from left to right.

This approach is efficient as it leverages a single scan of the list from right to left, and a simple comparison operation, making it optimal given the constraints of the problem.

Solutions

  • C++
  • Java
  • JavaScript
  • Python
cpp
class Solution {
public:
    vector<int> findOceanViewBuildings(vector<int>& heights) {
        int totalBuildings = heights.size();
        vector<int> result;
        int tallestSoFar = -1;
        
        for (int index = totalBuildings - 1; index >= 0; --index) {
            if (tallestSoFar < heights[index]) {
                result.push_back(index);
                tallestSoFar = heights[index];
            }
        }
        
        reverse(result.begin(), result.end());
        return result;
    }
};

The solution is designed to determine which buildings in a list have an unobstructed view of the ocean. The buildings are represented as a vector of integers where each integer denotes the height of a building. The buildings are evaluated from the perspective that the ocean is to the right of the last building in the array.

The approach used in this C++ solution is both efficient and straightforward, utilizing a single pass scan from right to left. This direction is chosen because a building will only have an ocean view if there are no taller buildings to its right. Here’s a breakdown of the solution:

  1. Initialize an empty vector result to store the indices of buildings with an ocean view.
  2. Start with tallestSoFar set to -1, which will track the height of the tallest building encountered so far from the right.
  3. Iterate through the buildings from right to left. For each building, compare its height with tallestSoFar:
    • If the current building is taller than tallestSoFar, it has an ocean view. Add the building's index to result and update tallestSoFar to the current building’s height.
  4. After the loop completes, reverse the result vector to present building indices in left-to-right order.
  5. Return the result vector.

The function returns a vector of indices of buildings that have an ocean view in an increasing order, enabling efficient identification of structures that meet the criteria.

java
class Solution {
    public int[] oceanViewBuildings(int[] buildings) {
        int total = buildings.length;
        ArrayList<Integer> visibleBuildings = new ArrayList<>();
        int highestYet = Integer.MIN_VALUE;
        
        for (int i = total - 1; i >= 0; i--) {
            if (buildings[i] > highestYet) {
                visibleBuildings.add(i);
                highestYet = buildings[i];
            }
        }
        
        int[] result = new int[visibleBuildings.size()];
        for (int j = 0; j < visibleBuildings.size(); j++) {
            result[j] = visibleBuildings.get(visibleBuildings.size() - 1 - j);
        }
        
        return result;
    }
}

The given Java solution aims to determine which buildings have an ocean view, given that they are all lined up from left to right and the ocean is to their right. The method oceanViewBuildings takes an array buildings where each element represents the height of a building.

Here's a succinct breakdown of the approach:

  • Start by assessing the buildings from right to left since the ocean is on the right side. This allows for immediate comparison with the last seen (or easternmost) building.
  • Utilize an integer highestYet initialized to Integer.MIN_VALUE to keep track of the highest building encountered as you iterate from the right. This tracking helps in determining which buildings have an unrestricted view of the ocean.
  • Use an ArrayList<Integer> visibleBuildings to store the indices of the buildings with an ocean view. A building has an ocean view if its height is greater than highestYet at that point.
  • Update highestYet whenever a taller building is found.
  • For the output, the indices in visibleBuildings need to be reversed because they were collected from right to left. Create an array result and populate it by iterating over visibleBuildings in reverse order.

Thus, the final output returns the indices of all buildings with an ocean view in left to right order, effectively solving the problem by leveraging a simple but efficient method of iterating in reverse and keeping track of the highest building seen so far.

js
let oceanViewBuildings = function(buildingHeights) {
    let totalBuildings = buildingHeights.length;
    let viewableBuildings = [];
    let tallestSeen = -1;

    for (let idx = totalBuildings - 1; idx >= 0; idx--) {
        if (tallestSeen < buildingHeights[idx]) {
            viewableBuildings.push(idx);
            tallestSeen = buildingHeights[idx];
        }
    }
    viewableBuildings.reverse();
    return viewableBuildings;
};

In the JavaScript solution provided, the goal is to identify buildings that have an unobstructed view of the ocean. The function oceanViewBuildings takes an array of integers, buildingHeights, each representing the height of a building from left to right as they face the ocean.

To find out which buildings have a clear view of the ocean:

  1. Initialize totalBuildings to the size of the buildingHeights array.
  2. Create an empty array viewableBuildings to store indices of buildings with ocean views.
  3. Use a variable tallestSeen initialized to -1 to keep track of the tallest building height encountered as you iterate from right to left.

Iterate over buildingHeights from the last building to the first:

  1. Compare tallestSeen with the current building's height.
  2. If the current building is taller than tallestSeen, add its index to viewableBuildings and update tallestSeen to this building's height.
  3. After finishing the loop, reverse the viewableBuildings array to ensure it represents buildings from left to right.

Return viewableBuildings, which now contains indices of all buildings that have an unobstructed view of the ocean. This solution efficiently traverses the list once in reverse to minimize computations and efficiently resolve the challenge.

python
class Solution:
    def getViewableBuildings(self, buildings: List[int]) -> List[int]:
        total = len(buildings)
        result = []
        tallest = -1

        for index in reversed(range(total)):
            if tallest < buildings[index]:
                result.append(index)
                tallest = buildings[index]

        result.reverse()
        return result

The solution for the "Buildings With an Ocean View" problem is written in Python3. It involves iterating over an array of building heights to determine which buildings have an unblocked view of the ocean. The strategy uses the following approach:

  • Initialize an empty list result to store the indices of buildings with an ocean view.
  • Start with a variable tallest set to -1, which will keep track of the tallest building encountered so far from the rightmost side of the list.
  • Iterate over the list of buildings in reverse order using a loop. For each building:
    • Compare the current building's height to the tallest. If the current building is taller, add its index to the result list and update tallest to this building's height.
  • After the loop, reverse the result list to present indices in left-to-right order.
  • Return the result, which contains indices of buildings with an ocean view.

This algorithm ensures that each building is checked against the maximum height found to its right, aligning with the idea that a building can see the ocean if it is taller than any building to its right. The use of reversal and tracking the highest structures optimizes the solution, making it efficient and straightforward to understand.

Comments

No comments yet.