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 −
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]))
[5, 6, 8, 7]