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 are 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.

Algorithm

To solve this, we will follow these steps −

  • Create an empty result list
  • Initialize maximum height seen so far as 0
  • Iterate from right to left (from the end of the array)
  • If current building height is greater than maximum height seen so far −
    • Add the current index to result list
    • Update maximum height to current building height
  • Return the reversed result list to get indices in proper order

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]

# Test with example
heights = [5, 6, 8, 7]
result = solve(heights)
print(f"Input: {heights}")
print(f"Output: {result}")
Input: [5, 6, 8, 7]
Output: [2, 3]

How It Works

The algorithm works by scanning from right to left and keeping track of the tallest building seen so far. When we encounter a building taller than any we've seen from the right, it means this building has an unobstructed view.

def solve_with_explanation(heights):
    res, h = [], 0
    print(f"Buildings: {heights}")
    print("Scanning from right to left:")
    
    for i in range(len(heights) - 1, -1, -1):
        print(f"Index {i}: Height {heights[i]}, Max height so far: {h}")
        if heights[i] > h:
            res.append(i)
            h = heights[i]
            print(f"  ? Building at index {i} has better view!")
        else:
            print(f"  ? Building at index {i} is blocked")
    
    result = res[::-1]
    print(f"Buildings with better view: {result}")
    return result

# Test the explanation
solve_with_explanation([5, 6, 8, 7])
Buildings: [5, 6, 8, 7]
Scanning from right to left:
Index 3: Height 7, Max height so far: 0
  ? Building at index 3 has better view!
Index 2: Height 8, Max height so far: 7
  ? Building at index 2 has better view!
Index 1: Height 6, Max height so far: 8
  ? Building at index 1 is blocked
Index 0: Height 5, Max height so far: 8
  ? Building at index 0 is blocked
Buildings with better view: [2, 3]

Another Example

# Test with different building heights
test_cases = [
    [1, 2, 3, 4, 5],
    [5, 4, 3, 2, 1],
    [3, 1, 4, 1, 5],
    [10]
]

for buildings in test_cases:
    result = solve(buildings)
    print(f"Buildings {buildings} ? Better view at indices: {result}")
Buildings [1, 2, 3, 4, 5] ? Better view at indices: [0, 1, 2, 3, 4]
Buildings [5, 4, 3, 2, 1] ? Better view at indices: [0]
Buildings [3, 1, 4, 1, 5] ? Better view at indices: [0, 2, 4]
Buildings [10] ? Better view at indices: [0]

Conclusion

This algorithm efficiently finds buildings with unobstructed views by scanning from right to left and tracking the maximum height. The time complexity is O(n) and space complexity is O(k) where k is the number of buildings with better views.

---
Updated on: 2026-03-26T14:35:02+05:30

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements