Houses and heaters stand at whole-number positions on a straight line. Every heater warms everything within the same distance r of it, on both sides.
Given the positions houses and heaters, return the smallest r that keeps every house warm. Neither list is sorted, and positions may repeat.
Example 1
Input: houses = [2, 5, 11], heaters = [10, 4] Output: 2 Why: house 2 is 2 from heater 4; the others are 1 away
2 more examples and the constraints
Example 2
Input: houses = [3, 8], heaters = [6] Output: 3 Why: house 3 is 3 away from the only heater
Example 3
Input: houses = [7, 4, 9], heaters = [1] Output: 8 Why: house 9 is the farthest, 8 away
Constraints
- 1 ≤ length of houses, length of heaters ≤ 30,000
- 1 ≤ houses[i], heaters[i] ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan every heaterO(n · m)
- Sort heaters + binary searchO((n + m) log m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 houses and heaters | Verdict |
|---|---|---|---|
| Scan every heater | O(n · m) | Mention it, then move on | |
| Sort heaters + binary search | O((n + m) log m) | Best; two neighbours |
n = number of houses, m = number of heaters.
Edge cases to test
- House on a heater. Its distance is 0; if that holds for every house, the answer is 0.
- No heater on one side. A house left of every heater has no left neighbour, and one right of every heater has no right one. Treat the missing side as infinitely far.
- Unsorted input. Neither list is sorted, so sort the heaters before searching.
- Far apart values. Positions near 1 and 1,000,000,000 give gaps close to 10⁹; that still fits in a 32-bit int.
Common mistakes
- Searching unsorted heaters, or forgetting to sort them at all.
- Reading
heaters[i]orheaters[i − 1]without checking that the index exists. - Taking the minimum over houses instead of the maximum: the worst-off house sets the radius.
How to talk through it
- 1Clarify. Are the lists sorted? Can positions repeat? Does every heater use the same radius?
- 2Reframe. The answer is the largest distance from a house to its nearest heater.
- 3Give the brute force. Check every heater for every house: O(n · m), too slow at 30,000 each.
- 4Search the neighbours. Sort the heaters; binary search gives the two candidates around each house.
- 5Test out loud. Run a house left of all heaters, one right of all heaters, and one sitting on a heater.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?