Leetcode #1918: Kth Smallest Subarray Sum
In this guide, we solve Leetcode #1918 Kth Smallest Subarray Sum in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Binary Search, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: nums = [2,1,3], k = 4
Output: 3
Explanation: The subarrays of [2,1,3] are:
- [2] with sum 2
- [1] with sum 1
- [3] with sum 3
- [2,1] with sum 3
- [1,3] with sum 4
- [2,1,3] with sum 6
Ordering the sums from smallest to largest gives 1, 2, 3, 3, 4, 6. The 4th smallest is 3.
Python Solution
class Solution:
def kthSmallestSubarraySum(self, nums: List[int], k: int) -> int:
def f(s):
t = j = 0
cnt = 0
for i, x in enumerate(nums):
t += x
while t > s:
t -= nums[j]
j += 1
cnt += i - j + 1
return cnt >= k
l, r = min(nums), sum(nums)
return l + bisect_left(range(l, r + 1), True, key=f)
Complexity
The time complexity is O(n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.