1511. Kth Smallest Window Peak

Medium3.5 points estimatedBinary SearchArrayCounting

A weather station logs one reading per day in the array nums. For every contiguous stretch of days (a window), the station records the peak, which is the largest reading inside that window. A stretch is counted once per start and end day, so equal peaks from different windows all count separately, and a single day is a window of its own.

List the peaks of all n(n+1)/2 windows in non-decreasing order and return the value at position k, counting from 1. Only the value is returned, so duplicates never cause ambiguity. The number of windows can exceed the range of a 32-bit integer, so k is a 64-bit value. Aim for O(n log n) time, using a binary search over the distinct readings, and O(n) extra space.

Example 1

Input:
nums = [3,1,2], k = 4
Output:
3
Explanation:

The six window peaks are 3, 1, 2, 3, 2, 3; sorted they read 1, 2, 2, 3, 3, 3 and the 4th is 3.

Example 2

Input:
nums = [5,5,5], k = 5
Output:
5
Explanation:

Every window has peak 5, so any position gives 5.

Example 3

Input:
nums = [-4,7,-2,0], k = 3
Output:
0
Explanation:

Window peaks are -4, 7, -2, 0, 7, 7, 0, 7, 7, 7; sorted they begin -4, -2, 0, and the 3rd is 0.

Constraints

1 ≤ n ≤ 105

-109 ≤ nums[i] ≤ 109

1 ≤ k ≤ n(n+1)/2

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 log 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…