Find k-th smallest subarray sum
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving skills in array processing, specifically understanding of subarray sum properties, selection and ranking of values, and computational complexity analysis.
Constraints
- 1 <= len(nums) <= 2 * 10^4
- 1 <= nums[i] <= 10^4
- 1 <= k <= len(nums) * (len(nums) + 1) // 2
- All elements in nums are positive integers
Examples
Input: ([2, 1, 3], 4)
Expected Output: 3
Explanation: The subarray sums are [2, 3, 6, 1, 4, 3]. Sorted they become [1, 2, 3, 3, 4, 6], so the 4th smallest sum is 3.
Input: ([5], 1)
Expected Output: 5
Explanation: There is only one non-empty subarray, [5], so its sum is the 1st smallest.
Input: ([1, 1, 1], 5)
Expected Output: 2
Explanation: The subarray sums are [1, 2, 3, 1, 2, 1]. Sorted they are [1, 1, 1, 2, 2, 3], and the 5th smallest is 2.
Input: ([4, 2, 1], 6)
Expected Output: 7
Explanation: The subarray sums are [4, 6, 7, 2, 3, 1]. Sorted they are [1, 2, 3, 4, 6, 7], so the 6th smallest is 7.
Hints
- Instead of generating every subarray sum, binary search on the answer value.
- For a fixed limit x, count how many subarrays have sum <= x using a sliding window. This works in linear time because all numbers are positive.