LeetCode 862: Shortest Subarray with Sum at Least K

Problem Description

Explanation:

To solve this problem, we can use a deque (double-ended queue) to maintain a monotonic increasing prefix sum array. We iterate over the input array nums, compute the prefix sums, and store them along with their corresponding indices in the deque. At each step, we check if the current prefix sum minus the smallest prefix sum in the deque is greater than or equal to k. If it is, we update the minimum length of subarray found so far. If not, we continue iterating and updating the deque.

Algorithm:

  1. Initialize variables: n as the length of nums, minLen to store the minimum subarray length found so far (initially set to n + 1), prefixSum array to store the prefix sums, and a deque deq to maintain a monotonic increasing prefix sum array.
  2. Initialize the deque deq with a tuple (0, -1) to represent the initial prefix sum of 0 at index -1.
  3. Iterate over the input array nums and compute the prefix sums, storing each prefix sum and its index in the deque.
  4. At each step, check if the current prefix sum minus the smallest prefix sum in the deque is greater than or equal to k.
  5. If yes, update minLen with the minimum length of subarray found so far.
  6. If not, continue iterating and updating the deque.
  7. Return minLen if a valid subarray is found; otherwise, return -1.

Time Complexity:

The time complexity of this algorithm is O(n) where n is the length of the input array nums.

Space Complexity:

The space complexity of this algorithm is O(n) to store the prefix sum array and the deque.

:

Solutions

class Solution {
    public int shortestSubarray(int[] nums, int k) {
        int n = nums.length;
        int minLen = n + 1;
        int[] prefixSum = new int[n + 1];
        Deque<Integer> deq = new LinkedList<>();
        deq.addLast(0);
        
        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
            while (!deq.isEmpty() && prefixSum[i + 1] - prefixSum[deq.peekFirst()] >= k) {
                minLen = Math.min(minLen, i - deq.pollFirst() + 1);
            }
            while (!deq.isEmpty() && prefixSum[i + 1] <= prefixSum[deq.peekLast()]) {
                deq.pollLast();
            }
            deq.addLast(i + 1);
        }
        
        return minLen == n + 1 ? -1 : minLen;
    }
}

Loading editor...