Skip to content

862. Shortest Subarray with Sum at Least K 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int shortestSubarray(vector<int>& nums, int k) {
    const int n = nums.size();
    int ans = n + 1;
    deque<int> dq;
    vector<long> prefix{0};

    for (int i = 0; i < n; ++i)
      prefix.push_back(prefix.back() + nums[i]);

    for (int i = 0; i < n + 1; ++i) {
      while (!dq.empty() && prefix[i] - prefix[dq.front()] >= k)
        ans = min(ans, i - dq.front()), dq.pop_front();
      while (!dq.empty() && prefix[i] <= prefix[dq.back()])
        dq.pop_back();
      dq.push_back(i);
    }

    return ans <= n ? ans : -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int shortestSubarray(int[] nums, int k) {
    final int n = nums.length;
    int ans = n + 1;
    Deque<Integer> dq = new ArrayDeque<>();
    long[] prefix = new long[n + 1];

    for (int i = 0; i < n; ++i)
      prefix[i + 1] = (long) nums[i] + prefix[i];

    for (int i = 0; i < n + 1; ++i) {
      while (!dq.isEmpty() && prefix[i] - prefix[dq.getFirst()] >= k)
        ans = Math.min(ans, i - dq.pollFirst());
      while (!dq.isEmpty() && prefix[i] <= prefix[dq.getLast()])
        dq.pollLast();
      dq.addLast(i);
    }

    return ans <= n ? ans : -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def shortestSubarray(self, nums: list[int], k: int) -> int:
    n = len(nums)
    ans = n + 1
    dq = collections.deque()
    prefix = list(itertools.accumulate(nums, initial=0))

    for i in range(n + 1):
      while dq and prefix[i] - prefix[dq[0]] >= k:
        ans = min(ans, i - dq.popleft())
      while dq and prefix[i] <= prefix[dq[-1]]:
        dq.pop()
      dq.append(i)

    return ans if ans <= n else -1