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 height 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 height 12 at index 2, from building height 10 at index 4 and from last building at index 5.

Algorithm

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))
[2, 4, 5]

How It Works

The algorithm uses a monotonic decreasing stack. For each building, we remove all previously seen buildings that are shorter or equal in height, since they cannot see the ocean. The remaining buildings in the stack can see the ocean because they are taller than all buildings to their right.

def solve_with_explanation(heights):
    stack = []
    print(f"Processing buildings: {heights}")
    
    for idx, h in enumerate(heights):
        print(f"\nBuilding at index {idx} with height {h}:")
        
        # Remove buildings that can't see ocean
        while stack and heights[stack[-1]] <= h:
            removed = stack.pop()
            print(f"  - Removing building at index {removed} (height {heights[removed]})")
        
        stack.append(idx)
        print(f"  - Current stack: {stack}")
    
    return stack

heights = [8, 12, 12, 9, 10, 6]
result = solve_with_explanation(heights)
print(f"\nFinal result: {result}")
Processing buildings: [8, 12, 12, 9, 10, 6]

Building at index 0 with height 8:
  - Current stack: [0]

Building at index 1 with height 12:
  - Removing building at index 0 (height 8)
  - Current stack: [1]

Building at index 2 with height 12:
  - Current stack: [1, 2]

Building at index 3 with height 9:
  - Current stack: [1, 2, 3]

Building at index 4 with height 10:
  - Removing building at index 3 (height 9)
  - Current stack: [1, 2, 4]

Building at index 5 with height 6:
  - Current stack: [1, 2, 4, 5]

Final result: [1, 2, 4, 5]

Conclusion

The monotonic stack approach efficiently finds buildings that can see the ocean by maintaining a decreasing stack of building indices. Buildings can see the ocean if no taller buildings exist to their right.

Updated on: 2026-03-26T16:43:49+05:30

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements