Skip to content
Problem 475 · LeetCode 475(opens in a new tab)

Heaters

MediumArrays

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.

Try it on LeetCode(opens in a new tab)
  1. Scan every heaterO(n · m)
  2. 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

ApproachTimeRelative work for 30,000 houses and heatersVerdict
Scan every heaterO(n · m)
Mention it, then move on
Sort heaters + binary searchO((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] or heaters[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

  1. 1Clarify. Are the lists sorted? Can positions repeat? Does every heater use the same radius?
  2. 2Reframe. The answer is the largest distance from a house to its nearest heater.
  3. 3Give the brute force. Check every heater for every house: O(n · m), too slow at 30,000 each.
  4. 4Search the neighbours. Sort the heaters; binary search gives the two candidates around each house.
  5. 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?