Problem Description
Given an integer array nums and an integer k, find the kth smallest subarray sum. A subarray is a non-empty contiguous sequence in the array and the subarray sum is the sum of its elements.
Key Insights
- All numbers in nums are positive, ensuring that subarray sums increase as more elements are added.
- The range of possible subarray sums lies between the smallest element and the sum of the entire array.
- Use Binary Search over this sum range to guess a candidate sum.
- For each candidate, count the number of subarrays which have sums less than or equal to it using the Sliding Window (two pointers) technique.
- Adjust the binary search boundaries based on the count relative to k.
Space and Time Complexity
Time Complexity: O(n log S) where n is the length of nums and S is the sum of all elements. Space Complexity: O(1) extra space (excluding the input array).
Solution
We use a binary search on the range of possible subarray sums. For each candidate sum (mid), we count how many contiguous subarrays have a sum less than or equal to mid using a sliding window approach. Because the array contains only positive integers, increasing the window always increases the sum. If the count is less than k, we know the kth smallest sum must be greater than mid; otherwise, it is less than or equal to mid. Finally, the binary search converges to the kth smallest subarray sum.