DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Updated on

LeetCode in Java: 209

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int sum = 0;
        int ans = Integer.MAX_VALUE;

        for (int l = 0, r = 0; r < nums.length; r++) {
            sum += nums[r];
            while (sum >= s) {
                ans = Math.min(ans, r - l + 1);
                sum -= nums[l++];
            }
        }

        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}

This problem is solved by using the two pointers l and r. In the for loop, we incrementally add the element at r to sum. Whenever the sum is greater or equal to s, we calculate the distance between the two pointers (r - l + 1) and if the distance is smaller than ans, we update ans with the distance. Then subtract the element at l from sum and increment l. At the end of the for loop, we should get the length of minimum subarray.

Time Complexity: O(n)

Extra Space: O(1)

Latest comments (0)