Using Sliding Window C++ Simple Solution


#1

The idea is we know that as we shift the right index diff increases and as we shift the left index diff decreases. So we create a window A[l,r] and shift it accordingly. Take care of discarding l==r cases!

int Solution::diffPossible(vector<int> &A, int B) {
    int wLeft = 0, wRight = 1; // Indexes for current window.
    
    while(wRight < A.size()){
        if(wLeft == wRight) wRight++; // For discarding i==j cases.
        else
        {
            if(A[wRight] - A[wLeft] == B)return 1;
            else if (A[wRight] - A[wLeft] <B) wRight++;
            else wLeft++;
        }
    }
    return 0;
}