Program to find out the buildings that have a better view in Python


Suppose, we are provided with an array that contains the heights of different buildings. The buildings are located on a line, and a building has a better view if it is not obstructed by another taller building. So provided the array containing heights, we have to find out the buildings that do not have other taller buildings to obstruct the view from them. The indices are returned from the array that satisfies the criteria.

So, if the input is like height = [5, 6, 8, 7], then the output will be [2, 3]. The buildings in array index 0 and 1 is obstructed by the building at index 2. The building at index 2 and 3 are not blocked because the taller building at position 2 is situated behind the shorter building at position 3.

To solve this, we will follow these steps −

  • res := a new list
  • h := 0
  • for i in range (size of heights - 1) to -1, decrease by 1, do
    • if heights[i] > h , then
      • insert i at the end of res
      • h := heights[i]
  • return the reverse of list res

Example

Let us see the following implementation to get better understanding −

def solve(heights):
   res, h = [], 0
   for i in range(len(heights) - 1, -1, -1):
      if heights[i] > h:
         res.append(i)
         h = heights[i]
   return res[::-1]

print(solve([5, 6, 8, 7]))

Input

[5, 6, 8, 7]

Output

[2, 3]

Updated on: 07-Oct-2021

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements