1512. Kth Subarray Total

Medium3.5 points estimatedBinary SearchSliding WindowPrefix Sum

A bakery records the number of loaves sold each day in the array nums; every entry is a positive whole number. Any run of consecutive days has a total, and runs that start or end on different days are different runs even when their totals are equal, so there are n(n+1)/2 totals in all.

Sort all of those totals from smallest to largest, with repeated totals kept, and return the one at position k, counting from 1. Only the total itself is returned, so equal totals never need a tie-break. Because a total can pass the 32-bit range for large inputs, return it as a 64-bit integer. Aim for O(n log S) time, where S is the sum of the whole array, and O(1) extra space beyond the input.

Example 1

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

The six totals are 2, 1, 3, 3, 4, 6; sorted they are 1, 2, 3, 3, 4, 6 and the 4th is 3.

Example 2

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

Totals are 4, 4 and 8, so the 2nd smallest is 4.

Example 3

Input:
nums = [5,1,1,5], k = 10
Output:
12
Explanation:

The largest of the ten totals is the whole array, 12.

Constraints

1 ≤ n ≤ 105

1 ≤ nums[i] ≤ 104

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 S)
Space
O(1)

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…