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 - 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
H1H2H3H4Heater AHeater B100 unitsMinimum Radius = 100(House H4 is 100 units from nearest heater)Algorithm Steps:1. Sort houses: [1, 2, 3, 15] and heaters: [2, 10]2. For each house, find distance to nearest heater: House 1: min(|1-2|, |1-10|) = 1 House 2: min(|2-2|, |2-10|) = 0 House 3: min(|3-2|, |3-10|) = 1 House 15: min(|15-2|, |15-10|) = 53. Maximum distance = 5 โ†’ Answer: radius = 5
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ 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
Asked in
Google 24 Amazon 18 Microsoft 12 Meta 8
26.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen