Heaters (LeetCode 475): Solution and Explanation
Houses and heaters sit on a line. Find the smallest radius, shared by every heater, that warms every house.
Intuition
Look at one house on its own. It is warm as soon as the radius reaches its nearest heater, so its personal need is the distance to that heater.
The shared radius has to satisfy every house at once, so the answer is the largest personal need. The house farthest from any heater is the bottleneck.
Finding the nearest heater by checking all of them is O(m) per house. Sort the heaters instead: the nearest one to a house is always one of the two heaters that sandwich it.
A binary search finds the first heater at or past the house. That heater and the one just before it are the only candidates.
Approach: Sort heaters, binary search per house
- Sort
heatersand setradius = 0. - For each house
h, binary search forlo, the first index whereheaters[lo] >= h. - If
lo < m, the right neighbour isheaters[lo] - haway. - If
lo > 0, the left neighbour ish - heaters[lo - 1]away. Take the smaller of the two as this house's need. - Set
radius = max(radius, need)and returnradiusat the end.
Step-by-step example
houses = [1,2,3], heaters = [2]
- Sorted heaters: [2]. radius = 0.
- House 1: the first heater at or past 1 is index 0 (heater 2), 1 away. No left neighbour. need = 1, radius = 1.
- House 2: the search lands on heater 2 itself, 0 away. radius stays 1.
- House 3: every heater is to its left; heater 2 is 1 away. radius stays 1. Return 1.
Code: Python, Java, C++
1class Solution:
2 def findRadius(self, houses: List[int], heaters: List[int]) -> int:
3 heaters.sort()
4 radius = 0
5 for h in houses:
6 lo, hi = 0, len(heaters)
7 while lo < hi:
8 mid = (lo + hi) // 2
9 if heaters[mid] < h:
10 lo = mid + 1
11 else:
12 hi = mid
13 best = 2 * 10**9
14 if lo < len(heaters):
15 best = heaters[lo] - h
16 if lo > 0:
17 best = min(best, h - heaters[lo - 1])
18 radius = max(radius, best)
19 return radius1class Solution {
2 public int findRadius(int[] houses, int[] heaters) {
3 Arrays.sort(heaters);
4 int radius = 0;
5 for (int h : houses) {
6 int lo = 0, hi = heaters.length;
7 while (lo < hi) {
8 int mid = (lo + hi) / 2;
9 if (heaters[mid] < h) {
10 lo = mid + 1;
11 } else {
12 hi = mid;
13 }
14 }
15 int best = Integer.MAX_VALUE;
16 if (lo < heaters.length) {
17 best = heaters[lo] - h;
18 }
19 if (lo > 0) {
20 best = Math.min(best, h - heaters[lo - 1]);
21 }
22 radius = Math.max(radius, best);
23 }
24 return radius;
25 }
26}1class Solution {
2public:
3 int findRadius(vector<int>& houses, vector<int>& heaters) {
4 sort(heaters.begin(), heaters.end());
5 int radius = 0;
6 for (int h : houses) {
7 int lo = 0, hi = heaters.size();
8 while (lo < hi) {
9 int mid = (lo + hi) / 2;
10 if (heaters[mid] < h) {
11 lo = mid + 1;
12 } else {
13 hi = mid;
14 }
15 }
16 int best = INT_MAX;
17 if (lo < (int)heaters.size()) {
18 best = heaters[lo] - h;
19 }
20 if (lo > 0) {
21 best = min(best, h - heaters[lo - 1]);
22 }
23 radius = max(radius, best);
24 }
25 return radius;
26 }
27};Time and space complexity
O((n + m) log m)
Sorting the heaters costs O(m log m) and each of the n houses runs one O(log m) binary search.
O(1)
Apart from the sort, only a few integers are stored.
Other approaches
Sort both and sweep with two pointers (time O(n log n + m log m), space O(1))
Sort houses and heaters, then move a heater pointer forward while the next heater is at least as close to the current house. Each pointer only moves forward.
Binary search on the radius (time O((n + m) log(max value)), space O(1))
Guess a radius and check in one sweep whether every house is covered, then binary search the smallest radius that works. Correct, but it adds a log of the value range on top of the sweep.
Brute force (time O(n * m), space O(1))
For every house, scan every heater for the minimum distance. Too slow at 3 * 10^4 each.
Common mistakes
- Forgetting the edge cases where the house is left of every heater (lo = 0) or right of every heater (lo = m). Only one neighbour exists then.
- Taking the minimum over houses instead of the maximum. The radius must cover the worst house, not the best.
- Only checking the heater the search lands on. The heater just before it can be closer.
- Not sorting the heaters before the binary search. The input order is arbitrary.
Frequently asked questions
Why is the nearest heater always one of the two neighbours in sorted order?
Any heater further left than the left neighbour is farther from the house, and the same holds on the right. So the closest one must be next to the house's insertion point.
Do the houses need to be sorted?
Not for the binary search approach. Each house is handled on its own. The two pointer alternative is the one that needs both lists sorted.
Can the answer be 0?
Yes. If every house stands exactly on a heater, every need is 0, so the radius is 0.