Kth Smallest Subarray Sum — LeetCode 1918 Python Solution

MediumLeetCode PremiumArrayBinary SearchSliding Window
Problem
#1918
Reading time
3 min

The 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.

Example

Input
nums = [2,1,3], k = 4
Output
3
Explanation
The subarrays of [2,1,3] are:

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1918. Kth Smallest Subarray Sum is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1918. Kth Smallest Subarray Sum?
LeetCode 1918. Kth Smallest Subarray Sum is rated Medium on LeetCode.
What topics does LeetCode 1918. Kth Smallest Subarray Sum cover?
LeetCode 1918. Kth Smallest Subarray Sum is tagged Array, Binary Search and Sliding Window on LeetCode.
Is LeetCode 1918. Kth Smallest Subarray Sum a premium problem?
Yes. LeetCode 1918. Kth Smallest Subarray Sum is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview