Heaters in Python

The heater radius problem is a classic optimization challenge where we need to find the minimum radius for heaters to warm all houses on a horizontal line. Given positions of houses and heaters, we calculate the smallest radius that ensures every house is within range of at least one heater.

For example, with houses at positions [1,2,3,4] and heaters at [1,4], the minimum radius is 1. House at position 1 is covered by heater at position 1, houses at positions 2 and 3 are covered by either heater (within radius 1), and house at position 4 is covered by the heater at position 4.

Algorithm Approach

To solve this problem efficiently, we follow these steps:

  • Sort both houses and heaters arrays for optimal searching

  • For each house, find the closest heater using binary search

  • Calculate the minimum distance from each house to its nearest heater

  • Return the maximum of all minimum distances (the bottleneck)

Implementation

Here's the complete solution using binary search for efficiency ?

from bisect import bisect_left

def find_radius(houses, heaters):
    houses.sort()
    heaters.sort()
    min_distances = []
    
    for house in houses:
        # Find insertion point for house in sorted heaters
        idx = bisect_left(heaters, house)
        min_dist = float('inf')
        
        # Check heater to the right
        if idx < len(heaters):
            min_dist = min(min_dist, abs(house - heaters[idx]))
        
        # Check heater to the left
        if idx > 0:
            min_dist = min(min_dist, abs(house - heaters[idx - 1]))
        
        min_distances.append(min_dist)
    
    return max(min_distances)

# Test the solution
houses = [1, 2, 3, 4]
heaters = [1, 4]
result = find_radius(houses, heaters)
print(f"Minimum heater radius: {result}")
Minimum heater radius: 1

How It Works

The algorithm uses bisect_left() to efficiently find where each house would be inserted in the sorted heaters array. This gives us the optimal position to check the two closest heaters:

  • Right heater: The heater at index idx (if exists)

  • Left heater: The heater at index idx - 1 (if exists)

Example Walkthrough

Let's trace through the example with houses [1,2,3,4] and heaters [1,4] ?

# Step by step execution
houses = [1, 2, 3, 4]
heaters = [1, 4]

print("House positions:", houses)
print("Heater positions:", heaters)
print("\nFinding minimum distance for each house:")

for house in houses:
    idx = bisect_left(heaters, house)
    distances = []
    
    # Check right heater
    if idx < len(heaters):
        right_dist = abs(house - heaters[idx])
        distances.append(f"right: {right_dist}")
    
    # Check left heater  
    if idx > 0:
        left_dist = abs(house - heaters[idx - 1])
        distances.append(f"left: {left_dist}")
    
    min_dist = min([abs(house - heaters[idx]) if idx < len(heaters) else float('inf'),
                    abs(house - heaters[idx - 1]) if idx > 0 else float('inf')])
    
    print(f"House {house}: {', '.join(distances)} ? min distance: {min_dist}")
House positions: [1, 2, 3, 4]
Heater positions: [1, 4]

Finding minimum distance for each house:
House 1: right: 0 ? min distance: 0
House 2: right: 2, left: 1 ? min distance: 1
House 3: right: 1, left: 2 ? min distance: 1
House 4: left: 3, right: 0 ? min distance: 0

The maximum minimum distance is 1, so the minimum heater radius is 1.

Time Complexity

The solution has O(n log m + m log m) time complexity, where n is the number of houses and m is the number of heaters. Sorting takes O(n log n + m log m), and binary search for each house takes O(n log m).

Conclusion

The heater radius problem is efficiently solved using binary search to find the closest heater for each house. The minimum radius needed is the maximum of all individual minimum distances, ensuring every house is adequately warmed.

Updated on: 2026-03-25T08:45:34+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements