Kth Smallest Subarray Sum - Problem
Given an integer array nums of length n and an integer k, return the kth 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.
Note: Subarrays are ordered by their sum values in ascending order. If two subarrays have the same sum, they are considered equal for ranking purposes.
Input & Output
Example 1 — 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 — Small Array
$
Input:
nums = [1,2], k = 1
›
Output:
1
💡 Note:
Subarrays: [1]→1, [1,2]→3, [2]→2. Sorted: [1,2,3]. The 1st smallest is 1.
Example 3 — Negative Numbers
$
Input:
nums = [-1,2,-3], k = 2
›
Output:
-3
💡 Note:
All subarrays: [-1]→-1, [-1,2]→1, [-1,2,-3]→-2, [2]→2, [2,-3]→-1, [-3]→-3. Sorted: [-3,-2,-1,-1,1,2]. The 2nd smallest is -2.
Constraints
- 1 ≤ nums.length ≤ 2000
- -5 × 104 ≤ nums[i] ≤ 5 × 104
- 1 ≤ k ≤ nums.length × (nums.length + 1) / 2
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array nums and target rank k
2
All Subarrays
Generate all contiguous subsequences and their sums
3
Kth Smallest
Find the kth element in sorted order
Key Takeaway
🎯 Key Insight: Binary search on answer space is more efficient than generating all sums
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code