Ski Ridge Backup Beacons
Count intervals assigning each index the second-highest rank
A ski resort has a row of emergency beacons. The integer array heights gives their elevations in row order.
For every contiguous interval containing at least two beacons, the resort designates a primary beacon and a backup beacon. Beacons in that interval are ranked by:
- Higher elevation first.
- For equal elevations, smaller original index first.
The first-ranked beacon is primary, and the second-ranked beacon is backup.
Return an integer array counts of the same length as heights, where counts[i] is the number of contiguous intervals in which beacon i is the backup. Indices are zero-based, and every interval is considered independently.
Examples
Example 1
Input: heights = [4,1,3] Output: [0,2,1]
For elevations [4, 1, 3], the two length-two intervals both select index 1 as backup. The interval covering the whole row selects index 2 as backup.
Example 2
Input: heights = [5,5,5] Output: [0,2,1]
All elevations are equal, so smaller indices rank ahead of larger ones. In each interval, the backup is its second index from the left.
Example 3
Input: heights = [-2] Output: [0]
A row containing one beacon has no interval with at least two beacons.
Constraints
- 1 <= heights.length <= 100000
- -1000000000 <= heights[i] <= 1000000000
- Each returned count fits in a signed 64-bit integer and is exactly representable as a JavaScript Number.
The intended solution takes O(n) time and O(n) auxiliary space. Elevation ties must use original indices, including during the right-to-left scan.
Hints
Show hint 1Hint 1
Treat elevation and the index tie-breaker as one strict ranking. An index is backup precisely when its interval contains exactly one index that outranks it.
Show hint 2Hint 2
For each index, find the nearest two outranking indices on each side. Split its intervals according to whether the one outranking beacon lies on the left or the right; two coordinated monotonic stacks can find these boundaries in linear time.
Follow-up questions
What an interviewer might ask once you have a working solution.
- How would you compute the sum of backup elevations over all intervals without returning the individual counts?
- For a fixed small rank k, can you extend the boundary method to count intervals in which each index has rank k?
Practice this with an AI interviewer
Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.
Start this problem