Problem
Given an integer array nums
of length n
and an integer k
, return thekth
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.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
n == nums.length
1 <= n <= 2 * 10^4
1 <= nums[i] <= 5 * 10^4
1 <= k <= n * (n + 1) / 2
Solution
Method 1 – Binary Search with Sliding Window
Intuition
The k-th smallest subarray sum can be found by binary searching the possible sum values and, for each candidate sum, counting how many subarrays have sum ≤ that value. The counting can be done efficiently using a sliding window since all elements are positive.
Approach
- Set left = min(nums), right = sum(nums).
- While left < right:
- Compute mid = (left + right) // 2.
- Count the number of subarrays with sum ≤ mid using a sliding window.
- If the count ≥ k, set right = mid; else, set left = mid + 1.
- Return left as the answer.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log S)
, where n is the length of nums and S is the sum of nums. Each binary search step counts subarrays in O(n). - 🧺 Space complexity:
O(1)
, only a few variables are used.