KatInterview

Minimum Relay Power for Full Network Coverage

Heaps, Sorting & SearchAuto-graded · 17 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary searchgreedysorting

Last updated

Tests binary search on the answer combined with a greedy coverage check to find the minimum broadcast power so every city is reachable from a central hub.

Minimum Relay Power for Full Network Coverage

You are deploying a linear network of relay stations along a single road. The stations are placed at integer positions on a number line. One station is designated the hub (the starting point of the broadcast). The hub transmits a signal that can reach any station within distance power of it. Every station that receives the signal also re-transmits it, extending coverage by the same power in either direction.

Formally, the reachable set grows as follows:

  • Start with the hub position.
  • Repeatedly add any station whose position is within power of any already-reachable station.
  • Repeat until no new station can be added.

You need all stations to be reachable from the hub.

Given the list of station positions stations and the index hub_index (0-based index into stations), find the minimum non-negative integer power such that every station in stations is reachable from the hub.

How the greedy coverage check works

Sort the stations by position. Starting from the hub, greedily extend coverage: from the current rightmost reachable position, jump to the farthest station still within power, then repeat. Do the same leftward. If at any point there is a gap larger than power between consecutive stations (in either direction from the hub), not all stations are reachable.

Constraints

  • 1 ≤ len(stations) ≤ 2000
  • -10^6 ≤ stations[i] ≤ 10^6
  • All station positions are distinct.
  • 0 ≤ hub_index < len(stations)
  • The answer is guaranteed to fit in a 32-bit signed integer.
  • If there is only one station (the hub), the answer is 0.

Examples

Example 1

Input: min_relay_power([0, 10, 20, 30, 45], 0)

Output: 15

Example 2

Input: min_relay_power([5, 1, 9, 3, 7], 2)

Output: 2

Example 3

Input: min_relay_power([42], 0)

Output: 0

Hints

Hint 1

Sort the stations by position first — the coverage check becomes a simple linear scan for gaps between consecutive stations.

Hint 2

Binary search on the answer: the feasibility function is monotone (if power p works, so does p+1), so binary the search space [0, max_gap_between_consecutive_sorted_stations].

Hint 3

For the coverage check, find the hub in the sorted order, then scan left and right: if any consecutive gap exceeds the candidate power, that power is insufficient.