Sliding Window Pattern – Part 2: Variations with Conditions

In Part 1, we covered the core fixed-size sliding window pattern: maintain a running sum, slide one element at a time, evaluate each window in O(1). The three problems we solved were almost identical in structure.

Now things get more interesting. The four problems in this post still use a fixed-size window, but each one adds a twist to what you track or how you evaluate the window. The underlying mechanics remain the same — the challenge is in decomposing the problem to recognize where the sliding window fits.


Problem 4: Diet Plan Performance (LC 1176)

Difficulty: Easy

Problem: A dieter consumes calories[i] on day i. For every consecutive sequence of k days, if total calories T > upper, gain 1 point; if T < lower, lose 1 point; otherwise, no change. Return total points.

Key Insight: This is the exact same window-sum pattern from Part 1, but the evaluation step has three branches instead of one. Instead of tracking a max or counting matches, you accumulate a score based on whether the window sum falls above, below, or between two thresholds.

Solution (C++)

cpp

class Solution {
public:
    int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {
        int calConsumed = accumulate(begin(calories), begin(calories) + k, 0);
        int points = calConsumed > upper ? 1 : calConsumed < lower ? -1 : 0;
        for (size_t i = k; i < calories.size(); ++i) {
            calConsumed -= calories[i-k];
            calConsumed += calories[i];
            points += calConsumed > upper ? 1 : calConsumed < lower ? -1 : 0;
        }

        return points;
    }
};

What’s Different?

Only the scoring logic changed. The ternary expression calConsumed > upper ? 1 : calConsumed < lower ? -1 : 0 replaces the simple comparison from LC 1343. The window slide mechanics (-= calories[i-k], += calories[i]) are identical.

Time: O(n)
Space: O(1)


Problem 5: Grumpy Bookstore Owner (LC 1052)

Difficulty: Medium

Problem: A bookstore owner has customers[i] customers arriving at minute i. The owner is grumpy during minute i if grumpy[i] == 1 (customers unsatisfied), and not grumpy if grumpy[i] == 0 (customers satisfied). The owner can use a secret technique to suppress grumpiness for minutes consecutive minutes — but only once. Maximize total satisfied customers.

Key Insight: This is where problem decomposition matters. Break it into two independent pieces:

  1. Always-satisfied customers: Sum of customers[i] where grumpy[i] == 0 — these are satisfied no matter what.
  2. Bonus from the technique: A sliding window of size minutes over the “grumpy” minutes. Within this window, unsatisfied customers become satisfied. Maximize this bonus.

The answer is always_satisfied + max_bonus. The sliding window only tracks the unsatisfied customers (where grumpy[i] == 1) within the current window.

Solution (C++)

cpp

class Solution {
public:
    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
        int numComplained = 0;
        int numSatisfied = 0;
        for (size_t i = 0; i < minutes; ++i) {
            numComplained += grumpy[i] == 1 ? customers[i] : 0;
            numSatisfied += grumpy[i] == 0 ? customers[i] : 0;
        }

        int maxComplained = numComplained;
        for (size_t i = minutes; i < customers.size(); ++i) {
            numSatisfied += grumpy[i] == 0 ? customers[i] : 0;
            numComplained -= grumpy[i-minutes] == 1 ? customers[i-minutes] : 0;
            numComplained += grumpy[i] == 1 ? customers[i] : 0;
            maxComplained = max(maxComplained, numComplained);
        }

        return numSatisfied + maxComplained;
    }
};

Walkthrough

For customers = [1,0,1,2,1,1,7,5] grumpy = [0,1,0,1,0,1,0,1] minutes = 3

  • numSatisfied accumulates customers at non-grumpy minutes across the entire array (not just the window).
  • numComplained is the sliding window tracking unsatisfied customers that the technique could save.
  • maxComplained tracks the best window — the optimal placement of the technique.

The key subtlety: numSatisfied is computed globally while the window slides, not just within the window. The first loop handles indices [0, minutes), and the second loop handles the rest. Both loops contribute to numSatisfied.

Time: O(n)
Space: O(1)


Problem 6: Maximum Number of Vowels in a Substring (LC 1456)

Difficulty: Medium

Problem: Given a string s and integer k, return the maximum number of vowel letters in any substring of length k.

Key Insight: Instead of a numeric sum, the window tracks a count of vowels. When a character enters the window, check if it’s a vowel and increment. When a character leaves, check and decrement. Same pattern, different “currency.”

Solution (C++)

cpp

class Solution {
public:
    int maxVowels(string s, int k) {
        unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u'};
        int numVowels = 0;
        for (size_t i = 0; i < k; ++i) {
            numVowels += vowels.find(s[i]) != end(vowels) ? 1 : 0;
        }

        int result = numVowels;
        for (size_t i = k; i < s.size(); ++i) {
            numVowels -= vowels.find(s[i-k]) != end(vowels) ? 1 : 0;
            numVowels += vowels.find(s[i]) != end(vowels) ? 1 : 0;
            result = max(result, numVowels);
        }

        return result;
    }
};

Pattern Recognition

Compare this to LC 643 (Maximum Average Subarray):

LC 643LC 1456
Window stateSum of numbersCount of vowels
Add elementsum += nums[i]count += isVowel(s[i])
Remove elementsum -= nums[i-k]count -= isVowel(s[i-k])
Evaluatemax(maxSum, sum)max(result, count)

The structure is identical. Only the definition of “what to add/remove” changes.

Time: O(n)
Space: O(1)


Problem 7: Find K-Length Substrings With No Repeated Characters (LC 1100)

Difficulty: Medium

Problem: Given a string s and integer k, return the number of substrings of length k with no repeated characters.

Key Insight: This is a sliding window problem, but the “window state” is now a hash map tracking character positions. When a duplicate is found, we can jump the start of the window forward to skip past the previous occurrence.

This problem bridges fixed-size and variable-size sliding windows. The window target is still k, but duplicates can shrink the valid region, so we track a startIdx that may jump forward.

Solution (C++)

cpp

class Solution {
public:
    int numKLenSubstrNoRepeats(string s, int k) {
        // key: letter
        // value: index of the observed letter
        unordered_map<char, int> observed;

        int startIdx = 0;
        int result = 0;
        for (size_t i = 0; i < s.size(); ++i) {
            auto it = observed.find(s[i]);
            // letter is found
            if (it != end(observed)) {
                startIdx = max(startIdx, it->second + 1);
                // update start index to current one to avoid repeat char
                it->second = i;
            } else {
                // letter is not found. update map with letter and index
                observed.insert(it, make_pair(s[i], i));
            }

            if (i - startIdx + 1 == k) {
                result += 1;
                ++startIdx;
            }
        }
        return result;
    }
};

How It Differs

Unlike the previous problems where we always subtract the [i-k] element, here the window start (startIdx) can jump forward when a repeat is detected. The map stores each character’s most recent index, so when we encounter a duplicate, we know exactly where to move startIdx.

Once the window reaches size k with no repeats (i – startIdx + 1 == k), we count it and advance startIdx by 1 to look for the next valid window.

Time: O(n)
Space: O(min(n, 26)) — at most 26 lowercase letters in the map


The Evolving Pattern

Across these four problems, the sliding window template stayed consistent, but the state and evaluation grew more complex:

ProblemWindow StateEvaluation
Diet Plan (1176)SumThree-way comparison
Grumpy Owner (1052)Two counters (satisfied + complained)Sum of global + max window
Max Vowels (1456)Vowel countTrack maximum
K-Length No Repeats (1100)Hash map of positionsCount valid windows

The takeaway: when you see a fixed-size subarray/substring problem, start with the basic template. Then ask yourself: what do I need to track in the window, and how do I evaluate it?

In Part 3, we’ll tackle the hardest problem in this series — Sliding Window Maximum — where the challenge isn’t the window itself, but efficiently maintaining the maximum within it.


Next up: Sliding Window Part 3 — The Monotonic Deque

Leave a Reply

Your email address will not be published. Required fields are marked *