DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

3 1

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)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay