KatInterview

892. Shortest Subarray with Sum at Least K

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the shortest contiguous non-empty subarray whose sum is at least k. The main challenge is the presence of negative numbers in the input array nums. If all numbers were positive, a standard sliding window approach would work efficiently. However, with negative numbers, removing an element from the start of the window can increase the sum, breaking the logic of a simple sliding window.

Solution

Shortest Subarray with Sum at Least K in Python

import collections

class Solution:
    def shortestSubarray(self, nums: List[int], k: int) -> int:
        n = len(nums)
        # Python integers handle arbitrary size, so no overflow issues with prefix sums.
        prefix_sum = [0] * (n + 1)
        for i in range(n):
            prefix_sum[i + 1] = prefix_sum[i] + nums[i]
            
        min_length = n + 1
        # Deque to store indices of prefix sums.
        dq = collections.deque()

        # Iterate through prefix sums. y corresponds to the index in the prefix_sum array.
        for y, p_y in enumerate(prefix_sum):
            # Maintain monotonic property of the deque based on prefix sum values.
            # If prefix_sum[y] <= prefix_sum[dq[-1]], dq[-1] is a worse candidate
            # for a starting index than y, because y is a later index giving a smaller or equal prefix sum.
            while dq and p_y <= prefix_sum[dq[-1]]:
                dq.pop()
            
            # Check for valid subarrays ending at y-1.
            # We want p_y - prefix_sum[x] >= k, where x is an index from the deque.
            while dq and p_y >= prefix_sum[dq[0]] + k:
                # Update min_length. The subarray is nums[x...y-1].
                min_length = min(min_length, y - dq[0])
                # We've found the shortest possible subarray starting at dq[0].
                # It can't be part of an even shorter subarray, so we remove it.
                dq.popleft()
            
            # Add the current index to the deque.
            dq.append(y)
            
        # If min_length wasn't updated, no valid subarray was found.
        return min_length if min_length <= n else -1

Shortest Subarray with Sum at Least K in Java

class Solution {
    public int shortestSubarray(int[] nums, int k) {
        int n = nums.length;
        // Use long for prefix sums to avoid integer overflow.
        long[] prefixSum = new long[n + 1];
        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }

        int minLength = n + 1;
        // Deque to store indices of prefix sums.
        Deque<Integer> dq = new ArrayDeque<>();

        // Iterate through prefix sums. y corresponds to the end of a potential subarray.
        for (int y = 0; y <= n; y++) {
            // Maintain the monotonic property of the deque.
            // If prefixSum[y] <= prefixSum[dq.peekLast()], then dq.peekLast() is a worse
            // candidate for a starting index than y.
            while (!dq.isEmpty() && prefixSum[y] <= prefixSum[dq.peekLast()]) {
                dq.pollLast();
            }

            // Check for valid subarrays ending at y-1.
            // We want prefixSum[y] - prefixSum[x] >= k, where x is an index from the deque.
            while (!dq.isEmpty() && prefixSum[y] >= prefixSum[dq.peekFirst()] + k) {
                // Update minLength. The subarray is nums[x...y-1].
                minLength = Math.min(minLength, y - dq.peekFirst());
                // We've found the shortest possible subarray starting at dq.peekFirst().
                // It can't be part of an even shorter subarray, so we remove it.
                dq.pollFirst();
            }
            
            // Add the current index to the deque.
            dq.offerLast(y);
        }

        // If minLength wasn't updated, no valid subarray was found.
        return minLength == n + 1 ? -1 : minLength;
    }
}

Shortest Subarray with Sum at Least K in C++

class Solution {
public:
    int shortestSubarray(vector<int>& nums, int k) {
        int n = nums.size();
        // Use long long for prefix sums to avoid overflow.
        vector<long long> prefixSum(n + 1, 0);
        for (int i = 0; i < n; ++i) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }

        int minLength = n + 1;
        // Deque to store indices of prefix sums.
        deque<int> dq;

        // Iterate through prefix sums. y is an index for the prefixSum array.
        for (int y = 0; y <= n; ++y) {
            // Maintain monotonic property of the deque.
            // If prefixSum[y] is smaller than or equal to the prefix sum at the back of the deque,
            // the back element is a worse candidate for a starting point than y.
            // A subarray starting at y will be shorter and have a potentially larger sum difference.
            while (!dq.empty() && prefixSum[y] <= prefixSum[dq.back()]) {
                dq.pop_back();
            }

            // Check if we can form a valid subarray.
            // Find the smallest x such that prefixSum[y] - prefixSum[x] >= k.
            // Since dq is monotonic, we check from the front.
            while (!dq.empty() && prefixSum[y] >= prefixSum[dq.front()] + k) {
                // Update minLength. The subarray is from index dq.front() to y-1.
                minLength = min(minLength, y - dq.front());
                // This dq.front() is the best possible start for a subarray ending at or before y.
                // We can discard it as it cannot form a shorter subarray with any future end index.
                dq.pop_front();
            }

            // Add current index to the deque.
            dq.push_back(y);
        }

        // If minLength was not updated, it means no valid subarray was found.
        return minLength == n + 1 ? -1 : minLength;
    }
};

Shortest Subarray with Sum at Least K in TypeScript

function shortestSubarray(nums: number[], k: number): number {
    const n = nums.length;
    // JS numbers are 64-bit floats. Sums up to 10^10 are safe from precision loss.
    const prefixSum: number[] = new Array(n + 1).fill(0);
    for (let i = 0; i < n; i++) {
        prefixSum[i + 1] = prefixSum[i] + nums[i];
    }

    let minLength = n + 1;
    // Deque to store indices of prefix sums. A simple array can act as a deque.
    const dq: number[] = [];

    // Iterate through prefix sums. y is an index for the prefixSum array.
    for (let y = 0; y <= n; y++) {
        // Maintain the monotonic property of the deque.
        // If prefixSum[y] <= prefixSum[dq[dq.length - 1]], the last element in dq is a worse
        // candidate for a starting index than y.
        while (dq.length > 0 && prefixSum[y] <= prefixSum[dq[dq.length - 1]]) {
            dq.pop(); // remove from back
        }

        // Check for valid subarrays ending at y-1.
        // We want prefixSum[y] - prefixSum[x] >= k, where x is an index from the deque.
        while (dq.length > 0 && prefixSum[y] >= prefixSum[dq[0]] + k) {
            // Update minLength. The subarray is nums[x...y-1].
            minLength = Math.min(minLength, y - dq[0]);
            // We've found the shortest possible subarray starting at dq[0].
            // It can't be part of an even shorter subarray, so we remove it.
            dq.shift(); // remove from front
        }
        
        // Add the current index to the deque.
        dq.push(y);
    }

    // If minLength wasn't updated, no valid subarray was found.
    return minLength === n + 1 ? -1 : minLength;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.