Heaters - Problem
Winter is Coming - The Heater Coverage Problem!
You're tasked with designing a heating system for a neighborhood! Given houses and heaters positioned along a straight line, you need to find the minimum radius that allows all heaters to warm every house.
The Challenge: All heaters must use the same radius, and every house must be within at least one heater's warming range.
Input: Two arrays -
Output: The minimum radius needed to cover all houses
Example: If houses are at [1, 2, 3] and heaters at [2], then radius 1 covers all houses (heater at 2 can warm houses 1, 2, and 3).
You're tasked with designing a heating system for a neighborhood! Given houses and heaters positioned along a straight line, you need to find the minimum radius that allows all heaters to warm every house.
The Challenge: All heaters must use the same radius, and every house must be within at least one heater's warming range.
Input: Two arrays -
houses (positions of houses) and heaters (positions of heaters)Output: The minimum radius needed to cover all houses
Example: If houses are at [1, 2, 3] and heaters at [2], then radius 1 covers all houses (heater at 2 can warm houses 1, 2, and 3).
Input & Output
example_1.py โ Basic Case
$
Input:
houses = [1,2,3], heaters = [2]
โบ
Output:
1
๐ก Note:
The only heater is at position 2. House 1 needs radius 1, house 2 needs radius 0, house 3 needs radius 1. Maximum radius needed is 1.
example_2.py โ Multiple Heaters
$
Input:
houses = [1,2,3,4], heaters = [1,4]
โบ
Output:
1
๐ก Note:
Houses 1 and 4 are covered by heaters directly (radius 0). House 2 is 1 unit from heater at 1. House 3 is 1 unit from heater at 4. Maximum radius needed is 1.
example_3.py โ Edge Case
$
Input:
houses = [1,5], heaters = [2]
โบ
Output:
3
๐ก Note:
The heater at position 2 needs radius 1 to reach house at 1, and radius 3 to reach house at 5. Maximum radius needed is 3.
Visualization
Tap to expand
Understanding the Visualization
1
Position Analysis
Map out all house and heater positions on a line
2
Find Nearest
For each house, identify the closest heater(s)
3
Calculate Radius
The maximum distance from any house to its nearest heater is the answer
Key Takeaway
๐ฏ Key Insight: Sort both arrays, then use two pointers to efficiently find each house's nearest heater. The maximum distance becomes our minimum required radius!
Time & Space Complexity
Time Complexity
O(n ร m)
For each of n houses, we check distance to all m heaters
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค houses.length, heaters.length โค 3 ร 104
- 1 โค houses[i], heaters[i] โค 109
- All values in houses are unique
- All values in heaters are unique
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code