BudiBadu Logo

Marina Beacon Frequency Search

Binary Search Easy 0 views
Like3

The marina control tower maintains a sorted list of beacon frequencies that can light the bay. When a patrol boat radios for assistance, it reports a minimum frequency that will cut through the fog. Operators must quickly find the lowest available beacon frequency that meets or exceeds the request; if none exists, they signal that the patrol should hold position until a stronger beacon can be tuned. The list is static for the evening, so the crew wants a quick lookup method to respond to multiple boats without scanning every entry by hand.

You are given the sorted frequency list and several boat requests. For each request, return the smallest frequency that is at least the requested value, or -1 when no such frequency exists. Implement the answer using binary search for each query, avoiding any modification of the original frequency list. This helps the tower confirm assignments, reserve power for higher beacons, and keep the harbor safe as mist drifts in.

Example 1:

Input: freqs = [10,20,35,50], requests = [5,20,36]
Output: [10,20,50]
Explanation: The closest frequencies meeting each request are 10, 20, and 50.

Example 2:

Input: freqs = [15,30,45], requests = [50,14]
Output: [-1,15]
Explanation: No beacon reaches 50, but 15 covers the 14 request.

Example 3:

Input: freqs = [], requests = [10]
Output: [-1]
Explanation: With no stored beacons, every request is unanswered.

Algorithm Flow

Recommendation Algorithm Flow for Marina Beacon Frequency Search - Budibadu
Recommendation Algorithm Flow for Marina Beacon Frequency Search - Budibadu

Best Answers

java
class Solution {
    public int marina_beacon_frequency_search(double[] nums, double target) {
        int low = 0, high = nums.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }
}