702894. Smallest subarray with sum greater than x

Easy

Here is the detailed Markdown blog post for the problem:

Smallest Subarray with Sum Greater Than x

Summary

Find the smallest subarray (contiguous segment) in an array that has a sum greater than a given integer x. This problem involves arrays and sliding window concepts.

Detailed Explanation


The problem can be solved by using a sliding window approach. The basic idea is to maintain two pointers, start and end, which represent the boundaries of the current subarray being considered. Initialize sum as 0 and min_length as infinity.

  1. Iterate through the array with the end pointer.
  2. Calculate the sum of the subarray from the start to the end using a variable temp_sum.
  3. If temp_sum is greater than x, update min_length if the current subarray length is smaller than min_length.
  4. Move the start pointer one step forward and subtract the element at the previous position from temp_sum. If temp_sum becomes negative, reset it to 0.
  5. Repeat steps 2-4 until the end of the array is reached.

Time Complexity Analysis: The time complexity of this algorithm is O(n), where n is the length of the input array. This is because we are performing a single pass through the array.

Space Complexity Analysis: The space complexity is O(1) as we are only using a constant amount of space to store the variables sum, min_length, and the two pointers.

Optimized Solutions


Java

View on GeeksforGeeks
public int findSmallestSubarray(int[] arr, int x) {
    int minLength = Integer.MAX_VALUE;
    int start = 0;
    int end = 0;
    int sum = 0;

    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
        while (sum > x) {
            if (i - start + 1 < minLength) {
                minLength = i - start + 1;
            }
            sum -= arr[start++];
        }
    }

    return minLength == Integer.MAX_VALUE ? -1 : minLength;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.