Skip to content

1918. Kth Smallest Subarray Sum 👍

  • Time: $O(n\log \Sigma |\texttt{nums[i]}|)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int kthSmallestSubarraySum(vector<int>& nums, int k) {
    int l = 0;
    int r = accumulate(nums.begin(), nums.end(), 0);

    while (l < r) {
      const int m = (l + r) / 2;
      if (numSubarrayLessThan(nums, m) >= k)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

 private:
  int numSubarrayLessThan(const vector<int>& nums, int m) {
    int res = 0;
    int sum = 0;
    for (int l = 0, r = 0; r < nums.size(); ++r) {
      sum += nums[r];
      while (sum > m)
        sum -= nums[l++];
      res += r - l + 1;
    }
    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int kthSmallestSubarraySum(int[] nums, int k) {
    int l = 0;
    int r = Arrays.stream(nums).sum();

    while (l < r) {
      final int m = (l + r) / 2;
      if (numSubarrayLessThan(nums, m) >= k)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  private int numSubarrayLessThan(int[] nums, int m) {
    int res = 0;
    int sum = 0;
    for (int l = 0, r = 0; r < nums.length; ++r) {
      sum += nums[r];
      while (sum > m)
        sum -= nums[l++];
      res += r - l + 1;
    }
    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def kthSmallestSubarraySum(self, nums: list[int], k: int) -> int:
    def numSubarrayLessThan(m: int) -> int:
      res = 0
      summ = 0
      l = 0
      for r, num in enumerate(nums):
        summ += num
        while summ > m:
          summ -= nums[l]
          l += 1
        res += r - l + 1
      return res

    return bisect.bisect_left(range(sum(nums)), k,
                              key=lambda m: numSubarrayLessThan(m))