Kth Smallest Subarray Sum Problem
Description
LeetCode Problem 1918.
Given an integer array nums of length n and an integer k, return the k^th smallest subarray sum.
A subarray is defined as a non-empty contiguous sequence of elements in an array. A subarray sum is the sum of all elements in the subarray.
Example 1:
Input: nums = [2,1,3], k = 4
Output: 3
Explanation: The subarrays of [2,1,3] are:
- [2] with sum 2
- [1] with sum 1
- [3] with sum 3
- [2,1] with sum 3
- [1,3] with sum 4
- [2,1,3] with sum 6
Ordering the sums from smallest to largest gives 1, 2, 3, 3, 4, 6. The 4th smallest is 3.
Example 2:
Input: nums = [3,3,5,5], k = 7
Output: 10
Explanation: The subarrays of [3,3,5,5] are:
- [3] with sum 3
- [3] with sum 3
- [5] with sum 5
- [5] with sum 5
- [3,3] with sum 6
- [3,5] with sum 8
- [5,5] with sum 10
- [3,3,5], with sum 11
- [3,5,5] with sum 13
- [3,3,5,5] with sum 16
Ordering the sums from smallest to largest gives 3, 3, 5, 5, 6, 8, 10, 11, 13, 16. The 7th smallest is 10.
Constraints:
n == nums.length1 <= n <= 2 * 10^41 <= nums[i] <= 5 * 10^41 <= k <= n * (n + 1) / 2
Solution
Approach: Binary Search on the Answer + Sliding Window
All numbers are positive, so the number of subarrays with sum at most s only grows as s grows. That lets us binary search the answer: it is the smallest s for which at least k subarrays have sum at most s.
The search range is from min(nums) to sum(nums). To count subarrays with sum at most s, use a sliding window: extend the right end i, add nums[i] to the window sum, and while the sum exceeds s move the left end j forward. Every subarray ending at i and starting in [j, i] qualifies, so add i - j + 1 to the count.
If the count is at least k, s is large enough, so keep it and search lower; otherwise search higher.
Complexity: O(n log S) time, where S is the sum of the array, and O(1) extra space.
class Solution:
def kthSmallestSubarraySum(self, nums: List[int], k: int) -> int:
def f(s):
t = j = 0
cnt = 0
for i, x in enumerate(nums):
t += x
while t > s:
t -= nums[j]
j += 1
cnt += i - j + 1
return cnt >= k
l, r = min(nums), sum(nums)
while l < r:
mid = (l + r) >> 1
if f(mid):
r = mid
else:
l = mid + 1
return l