Heaters (LeetCode 475): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Sorting

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

  1. Sort heaters and set radius = 0.
  2. For each house h, binary search for lo, the first index where heaters[lo] >= h.
  3. If lo < m, the right neighbour is heaters[lo] - h away.
  4. If lo > 0, the left neighbour is h - heaters[lo - 1] away. Take the smaller of the two as this house's need.
  5. Set radius = max(radius, need) and return radius at the end.

Step-by-step example

houses = [1,2,3], heaters = [2]
  1. Sorted heaters: [2]. radius = 0.
  2. House 1: the first heater at or past 1 is index 0 (heater 2), 1 away. No left neighbour. need = 1, radius = 1.
  3. House 2: the search lands on heater 2 itself, 0 away. radius stays 1.
  4. 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 radius
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.