Standard Two Pointers Solution with Explanation in Comments using C++


  • 0
    H
    class Solution {
    public:
    int minSubArrayLen(int s, vector<int>& nums) {
        // initilaize two pointers and current sum as zeros
        int ptr1 = 0;
        int ptr2 = 0;
        int cur_sum = 0;
        // initialize the arrayLen to the one greater than the size
        // of the input array "nums"
        int arrayLen = nums.size()+1;
        // as long as the last pointer is smaller the size
        // we will keep checking
        while(ptr1<nums.size()){
            // the cur_sum is not enough
            // and the second pointer is not greater than
            // the size we will add a new number to the cur_sum
            if(s>cur_sum && ptr2<nums.size() ){
                cur_sum += nums[ptr2];
                ptr2++;
            // else if the the cur_sum is greater than/or equal
            // to the target sum, we checked the length of current "window"
            // by taking the different betwee two pointer and add one
            // if the curren "window" size is less than the previous one
            // we update this size to the smallest one
            }else if(s<=cur_sum){
                 if(arrayLen >(ptr2-ptr1)){
                    arrayLen = ptr2-ptr1;
                 }
                cur_sum -=nums[ptr1];
                ptr1++;
            // if the second pointer already reached to the end
            // and cur_sum is still less than the target sum
            // then there is no way to increase the cur_sum
            // so we break out of the while loop.
            }else if(ptr2 == nums.size() && cur_sum<s){
                break;
            }
        }
        // return the result,
        // the question asks us to return zero
        // for any impossible cases.
        if(arrayLen == nums.size()+1){
            return 0;
        }else{
            return arrayLen;
        }
    }
    };

Log in to reply
 

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