← Back to LeetCode Notes

Sliding window

how code always works

10 sec read

how code always works

C++
string function(vector<int> arr) {    int l = 0;    // pick ONE structure based on what the invariant tracks:    int sum = 0;  // numeric constraint (>= target)    unordered_map<char, int> window_freq;  // uniqueness / char frequency    // have/need pair                  // multiset coverage (contains all    // of t)    deque<int> dq;  // sliding-window max/min (stores indices)    int best = 0;   // or INT_MAX if minimizing    // r is the driver: moves once per step, never rewinds, each element    // enters once    for (int r = 0; r < arr.size(); r++) {        // 1. r enters the window. update the structure to restore the        // invariant.        //    sum += arr[r];   or   window_freq[arr[r]]++;   etc.        // 2. move l. pick ONE rule per problem:        // RULE A - shrink WHILE valid, record best as you go.        //   for MINIMIZING a valid window (min subarray, min window        //   substring) while (valid) { best = min(best, r-l+1); remove        //   arr[l]; l++; }        // RULE B - shrink UNTIL valid again, record best after.        //   for MAXIMIZING under a constraint (longest substring no        //   repeat) while (invalid) { remove arr[l]; l++; } best =        //   max(best, r-l+1);        // RULE C - never shrink, only slide l when needed.        //   when best is monotonic and a stale window can't log a false        //   answer (character replacement). window length only grows.    }    return "";}