Kth Smallest Subarray Sum - Problem
You're given an integer array nums of length n and an integer k. Your task is to find the kth smallest subarray sum among all possible subarrays.
A subarray is a contiguous sequence of elements within the array - for example, in array [1, 2, 3, 4], some subarrays are [1], [2, 3], [1, 2, 3, 4], etc. The subarray sum is simply the sum of all elements in that subarray.
Goal: Among all n(n+1)/2 possible subarray sums, return the kth smallest one (1-indexed).
Example: For nums = [2, 1, 3] and k = 4, the subarray sums are: [2] = 2, [1] = 1, [3] = 3, [2,1] = 3, [1,3] = 4, [2,1,3] = 6. Sorted: [1, 2, 3, 3, 4, 6]. The 4th smallest is 3.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [2, 1, 3], k = 4
โบ
Output:
3
๐ก Note:
All subarrays: [2]=2, [2,1]=3, [2,1,3]=6, [1]=1, [1,3]=4, [3]=3. Sorted sums: [1,2,3,3,4,6]. The 4th smallest is 3.
example_2.py โ Single Element
$
Input:
nums = [5], k = 1
โบ
Output:
5
๐ก Note:
Only one subarray [5] with sum 5, so the 1st smallest is 5.
example_3.py โ All Equal Elements
$
Input:
nums = [3, 3, 3], k = 2
โบ
Output:
3
๐ก Note:
Subarrays: [3]=3, [3,3]=6, [3,3,3]=9, [3]=3, [3,3]=6, [3]=3. Sorted: [3,3,3,6,6,9]. The 2nd smallest is 3.
Constraints
- 1 โค nums.length โค 2000
- 1 โค nums[i] โค 5 ร 104
- 1 โค k โค nums.length ร (nums.length + 1) / 2
- All elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Set the range
Minimum pages = shortest book, Maximum pages = all books combined
2
Make a guess
Try the middle value: 'How many sessions have โค this many pages?'
3
Count efficiently
Use a sliding window approach to count sessions without listing them all
4
Adjust and repeat
If count < k, guess higher; if count โฅ k, guess lower until exact
Key Takeaway
๐ฏ Key Insight: Binary search on the answer space + efficient counting eliminates the need to generate and sort all subarray sums, reducing complexity from O(nยฒ log n) to O(n log(sum)).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code