# Accepted clean Java O(n) solution (two pointers)

• ``````public int minSubArrayLen(int s, int[] a) {
if (a == null || a.length == 0)
return 0;

int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;

while (j < a.length) {
sum += a[j++];

while (sum >= s) {
min = Math.min(min, j - i);
sum -= a[i++];
}
}

return min == Integer.MAX_VALUE ? 0 : min;
}``````

• This post is deleted!

• This post is deleted!

• min = Math.min(min, j - i + 1); would work if you use an outer for loop (j=0;j<a.length;j++) instead of while(j < a.length)

• sum += a[j++];
here, j is already increased 1, so no need to add 1 again when calculate the length.

• I think initialize min with a.length + 1 is OK here.

If the min value remains a.length + 1 in the end, just return 0.

• more simple than my solution.

• okay, O(2n) = O(n)

• came up with the similar solution as yours. easy understanding and clean.

• I like this version
clean code!

Translated to python

``````import sys
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
right = left = 0
minL = sys.maxsize
sumV = 0
while right < len(nums):
sumV += nums[right]
right+=1
while sumV >= s:
minL = min (minL , right-left)
sumV -=  nums[left]
left+=1
if minL == sys.maxsize:
return 0
return minL

``````

• Just consider an extreme case, what if j-i =Integer.MAX_VALUE? so the min should be Integer.MAX_VALUE and not be zero, is that right?

• @miceteat Because there is j++ before the while loop, so j-i is enough.

• @icezhou0784 I highly doubt there would be an array of size >= 2^31

• Perhaps could make it more readable. Thanks for sharing!

``````    public int minSubArrayLen(int s, int[] nums) {
int sum = 0, from = 0, win = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
while (sum >= s) {
win = Math.min(win, i - from + 1);
sum -= nums[from++];
}
}
return (win == Integer.MAX_VALUE) ? 0 : win;
}
``````

• This solution using two pointers is actually wrong
See https://discuss.leetcode.com/topic/62885/wrong-test-cases

Give u an counter-example
input:
7
[-1, 3, 4, 1]

• @jingxiao

The assumption is that there's no negative number in the array:

"Given an array of n positive integers and a positive integer s"

• could someone explain why it's o(n)?

• @qingemeng Do you ask due to a doubt about the two pointers? There are two pointers but both of them go forward (no backtracking) . In fact, this is O(2n) which also means O(n).

• @kilicars but it's two while loops, should it be n^2?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.