Program to find buildings from where sea can be visible in Python


Suppose we have a list of heights of different buildings. A building with heights value heights[i] can see the ocean when every building on its right are shorter than that building. We have to find the building indices from where we can see the ocean, in ascending order.

So, if the input is like heights = [8, 12, 12, 9, 10, 6], then the output will be [2, 4, 5] because we can see the ocean from building heights 12 at index 2, from building height 10 at index 10 and from last building at index 5.

To solve this, we will follow these steps −

  • stack := a new list
  • for each index idx and height h in heights, do
    • while stack is not empty and heights[top of stack ] <= h, do
      • delete last element from stack
  • push idx into stack
  • return stack

Example

Let us see the following implementation to get better understanding −

def solve(heights):
   stack = []
   for idx, h in enumerate(heights):
      while stack and heights[stack[-1]] <= h:
         stack.pop()
      stack.append(idx)
   return stack

heights = [8, 12, 12, 9, 10, 6]
print(solve(heights))

Input

[8, 12, 12, 9, 10, 6]

Output

[2, 4, 5]

Updated on: 14-Oct-2021

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements