LeetCode 475: Heaters Solution

Master LeetCode problem 475 (Heaters), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Sort the arrays houses and heaters.
  2. For each house, find the closest heater to the left and the closest heater to the right.
  3. Calculate the distance between the house and the closest heater.
  4. The minimum radius needed to cover all houses will be the maximum distance calculated in step 3.

Time complexity: O(nlogn) where n is the total number of houses and heaters. Space complexity: O(1)

Solution Code

import java.util.Arrays;

class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);
        
        int radius = 0;
        for (int house : houses) {
            int closestHeaterDist = Integer.MAX_VALUE;
            for (int heater : heaters) {
                closestHeaterDist = Math.min(closestHeaterDist, Math.abs(house - heater));
            }
            radius = Math.max(radius, closestHeaterDist);
        }
        
        return radius;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 475 (Heaters)?

This page provides optimized solutions for LeetCode problem 475 (Heaters) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 475 (Heaters)?

The time complexity for LeetCode 475 (Heaters) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 475 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 475 in Java, C++, or Python.

Back to LeetCode Solutions