Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum radius to light up all houses on a street in Python
Suppose we have a list of numbers called nums that represent positions of houses on a 1-dimensional line. We have 3 street lights that can be placed anywhere, and a light at position x with radius r lights up all houses in range [x - r, x + r], inclusive. We need to find the smallest radius r required to light up all houses.
For example, if the input is nums = [4, 5, 6, 7], then the output will be 0.5. We can place the lamps at positions 4.5, 5.5, and 6.5 with radius r = 0.5 to light up all 4 houses.
Approach
We use binary search to find the minimum radius. For each candidate radius, we check if it's possible to cover all houses with 3 lights using a greedy approach.
Algorithm Steps
The solution involves two main functions ?
Helper Function: valid(r)
This function checks if a given radius r can light up all houses with 3 lights ?
Place the first light at
nums[0] + r(rightmost position to cover the first house)For each subsequent house, if it's not covered by the current light, place a new light
Return
Trueif we need ? 3 lights,Falseotherwise
Main Function: Binary Search
We perform binary search on the radius value ?
Sort the house positions
Set search bounds:
left = 0,right = max_positionUse binary search to find the minimum valid radius
Example
class Solution:
def solve(self, nums):
def valid(r):
last_location = nums[0] + r
count = 1
for i in range(len(nums)):
val = nums[i]
if val - last_location > r:
count += 1
last_location = val + r
return count <= 3
nums.sort()
left = 0
right = nums[-1]
res = float("inf")
itr = 0
while left <= right and itr < 20:
mid = left + (right - left) / 2
if valid(mid):
res = min(res, mid)
right = mid
else:
left = mid
itr += 1
return res
# Test the solution
ob = Solution()
nums = [4, 5, 6, 7]
print(f"Input: {nums}")
print(f"Output: {ob.solve(nums)}")
Input: [4, 5, 6, 7] Output: 0.5
How It Works
For the input [4, 5, 6, 7] ?
Binary search tries different radius values
For
r = 0.5: Place lights at 4.5, 5.5, 6.5 ? covers all houses with 3 lights ?For
r : Would need more than 3 lights ?Therefore, minimum radius is
0.5
Key Points
Greedy placement: Always place lights at the rightmost valid position
Binary search: Efficiently finds the minimum radius
Time complexity: O(n log n) for sorting + O(n log max_position) for binary search
Space complexity: O(1) extra space
Conclusion
This solution combines binary search with a greedy approach to find the minimum radius needed to light up all houses with exactly 3 street lights. The key insight is using greedy placement to minimize the number of lights needed for any given radius.
