Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.

Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.

Notice that all the heaters follow your radius standard, and the warm radius will be the same.

Input & Output

Example 1 — Basic Case
$ Input: houses = [1,2,3], heaters = [2]
Output: 1
💡 Note: The only heater is at position 2. House at 1 needs radius 1, house at 2 needs radius 0, house at 3 needs radius 1. Maximum radius needed is 1.
Example 2 — Multiple Heaters
$ Input: houses = [1,2,3,4], heaters = [1,4]
Output: 1
💡 Note: Houses at positions 1 and 4 are covered by heaters. House at 2 is closest to heater at 1 (distance 1), house at 3 is closest to heater at 4 (distance 1). Maximum radius needed is 1.
Example 3 — Single House
$ Input: houses = [1], heaters = [1,2,3,4]
Output: 0
💡 Note: The house at position 1 has a heater at the exact same position, so radius 0 is sufficient.

Constraints

  • 1 ≤ houses.length, heaters.length ≤ 3 × 104
  • 1 ≤ houses[i], heaters[i] ≤ 109

Visualization

Tap to expand
Heaters Problem - Minimum Radius INPUT 1 2 3 H pos: 2 Legend = House = Heater houses [1, 2, 3] heaters [2] Warm all houses with minimum radius ALGORITHM STEPS 1 Sort Arrays Sort houses and heaters 2 For Each House Find nearest heater 3 Calculate Distance min(left, right heater) 4 Take Maximum max distance = radius Distance Calculations House Heater Dist 1 2 |1-2|=1 2 2 |2-2|=0 3 2 |3-2|=1 FINAL RESULT H 1 2 3 r=1 Output 1 Verification max(1, 0, 1) = 1 Radius 1 covers all OK - All houses warm! Key Insight: Binary search finds the closest heater for each house efficiently. The minimum radius must be the MAXIMUM of all minimum distances (to cover the farthest house). Time: O(n log n + m log m) for sorting + O(n log m) for binary search lookups. TutorialsPoint - Heaters | Optimal Solution (Binary Search)
Asked in
Google 15 Amazon 12
38.0K Views
Medium Frequency
~25 min Avg. Time
1.1K 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