VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-buildings-with-an-ocean-view/

⇱ Find Buildings With an Ocean View - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Buildings With an Ocean View

Last Updated : 11 Apr, 2024

Given a list of n buildings in a line, each building's height is given in heights[] array. Find and return the indices (0-indexed) of buildings with an unobstructed "ocean view," meaning they can see the ocean without taller buildings blocking their view to the right. The task is to return the indices (0-indexed) of the buildings that have an ocean view, sorted in increasing order.

Example:

Input: heights = {4,2,3,1}
Output: {0,2,3}

Input: heights = {4,3,2,1}
Output: {0,1,2,3}

Approach:

The idea is to use a right-to-left approach, starting from the rightmost building and moving towards the left. Maintains a variable tallestBuildingSoFar or maxx to keep track of the tallest building encountered so far. For each building, checks if its height is greater than maxx. If it is, the building has an ocean view and its index is added to the result vector. The maxx is then updated to the current building’s height if it’s greater. After iterating through all the buildings, the result[] array contains the indices of the buildings with an ocean view in descending order. Therefore, the vector is reversed to get the indices in ascending order.

Steps-by-step approach:

  • Create a variable tallestBuildingSoFar to keep track of the tallest building encountered from the right, starting with a minimum integer value.
  • Iterate over the heights array from right to left using a for loop.
    • For each building, check if it is taller than the tallest building encountered so far.
      • If the current building is taller, add its index to the result[] array and update the tallestBuildingSoFar value.
  • After iterating through all buildings, reverse the result[] array to get the indices in ascending order.
  • Return the result[] array containing the indices of buildings with an ocean view.

Below are the implementation of the above approach:


Output
2 4 

Time Complexity: O(n), where n is the number of buildings.
Auxililary Space: O(n)


Comment
Article Tags:
Article Tags: