Accepted clean Java O(n) solution


  • 2
    public int minSubArrayLen(int s, int[] a) {
      if (a == null || a.length == 0)
        return 0;
      
      // i is slow pointer, j is fast pointer
      int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
      
      while (j < a.length) {
        sum += a[j];
        
        // keep adding a[j] till sum >= s
        while (sum >= s) {
          min = Math.min(min, j - i + 1);
          // keep subtracting a[i] till sum < s
          sum -= a[i++];
        }
        
        j++;
      }
      
      return min == Integer.MAX_VALUE ? 0 : min;
    }

Log in to reply
 

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