1697. Fading Beacon Strength

Medium3.5 points estimatedMonotonic QueueSliding WindowQueueArray

Beacons stand at positions 0 to n-1 along a coast, where power[j] (possibly negative) is the strength of beacon j. At position i the signal of beacon j has strength power[j] - decay * |i - j|, and a beacon is heard only when |i - j| <= reach. Every position hears at least its own beacon. Return a long[] whose entry i is the strongest signal heard at position i. A direct scan costs O(n * reach), which is too slow for large inputs; split the neighbourhood into a left and a right half and answer each with a sliding-window maximum over a monotonic deque, in O(n) time and O(n) space. Use 64-bit arithmetic.

Example 1

Input:
power = [5,0,9], decay = 3, reach = 1
Output:
[5,6,9]
Explanation:

Position 0 keeps its own 5; position 1 hears 9 - 3 = 6 from the right (better than 0 and 5 - 3 = 2); position 2 keeps its own 9.

Example 2

Input:
power = [10,-4,2,8], decay = 2, reach = 2
Output:
[10,8,6,8]
Explanation:

Position 1 hears 10 - 2 = 8 from the left; position 2 hears 10 - 4 = 6 from beacon 0 and 8 - 2 = 6 from beacon 3, while the endpoints keep their own 10 and 8.

Example 3

Input:
power = [3,-7,1], decay = 5, reach = 0
Output:
[3,-7,1]
Explanation:

With reach 0 nothing is heard from other beacons, so every position receives only its own beacon.

Constraints

1 ≤ power.length ≤ 2 * 105

0 ≤ decay ≤ 104

0 ≤ reach ≤ power.length

-109 ≤ power[j] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…