Sliding Window Patterns

Sliding Window Patterns

209. Minimum Size Subarray Sum

Given an array of positive numbers and a value s, find the minimum length of a continuous subarray whose sum is ≥ s. Return 0 if none exists.

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int n=nums.size();
        int res = n+1;
        int l=0;
        // r moves first
        for(int r=0;r<n;++r) {
            s-=nums[r];
            while(s<=0) {
                // s<=0 means the sum of elements from l to r is exactly ≥ s
                // take minimum, then move l forward
                res = min(res, r-l+1);
                s+=nums[l++];
            }
        }
        return res % (n+1);
    }
};

1248. Count Number of Nice Subarrays

Return the number of continuous subarrays that contain exactly k odd numbers.

class Solution {
public:
    int numberOfSubarrays(vector<int>& nums, int k) {
        int n = nums.size();
        int count = 0;
        vector<int> m;
        m.push_back(-1);
        for(int i=0;i<n;++i) {
            if (nums[i]&1) m.push_back(i);
        }
        m.push_back(n);
        if (m.size()-2 < k) return 0;
        
        int l=1;
        int r=k;
        while(r<m.size()-1) {
            int a = m[l] - m[l-1] - 1;
            int b = m[r+1] - m[r] - 1;
            count += 1 + a + b + a*b;
            ++l;
            ++r;
        }
        return count;
    }
};

1234. Replace the Substring for Balanced String

A string contains only four characters. If each character appears exactly length/4 times, it’s balanced. Find the shortest substring to replace to make the original string balanced.

class Solution {
public:
    int balancedString(string s) {
        unordered_map<int, int> count;
        count.insert({'Q', 0});
        count.insert({'W', 0});
        count.insert({'E', 0});
        count.insert({'R', 0});
        for(int c : s) count[c]++;
        
        int i=0;
        int n=s.size();
        int k=n/4;
        int res = n;
        for(int j=0;j<n;++j) {
            // occurrences outside the window
            count[s[j]]--;
            // satisfy <=k condition
            while(i<n && count['Q']<=k && count['W']<=k && count['E']<=k && count['R']<=k) {
                // take minimum result
                res = min(res, j-i+1);
                // until condition is not satisfied
                count[s[i++]]++;
            }
        }
        if (res == n) return 0;
        return res;
    }
};