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: -2
💡 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
Kth Smallest Subarray Sum INPUT Array: nums 2 i=0 1 i=1 3 i=2 Input Values: nums = [2, 1, 3] k = 4 n = 3 All Subarrays: [2]=2, [1]=1, [3]=3 [2,1]=3, [1,3]=4 [2,1,3]=6 Total: 6 subarrays ALGORITHM STEPS 1 Generate Sums Find all subarray sums 2 Collect Sums Sums: [2,1,3,3,4,6] 3 Sort Sums Sorted: [1,2,3,3,4,6] 4 Return k-th Return sorted[k-1] Sorted Sums Array: 1 k=1 2 k=2 3 k=3 3 k=4 4 k=5 6 k=6 4th smallest FINAL RESULT The 4th smallest sum is: 3 Verification: Sorted sums: [1, 2, 3, 3, 4, 6] Position k=4 (0-indexed: 3) sorted[3] = 3 OK - Output: 3 Key Insight: For small arrays, enumerate all O(n^2) subarrays, calculate sums, sort them, and return the k-th element. For larger inputs, use binary search on the answer range with counting to achieve O(n^2 log(sum)) complexity. TutorialsPoint - Kth Smallest Subarray Sum | Optimal Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen