← Two PointersDSA 1.1.F

Sliding Window Hybrid

Variable-size window, expand right / shrink left. Minimum Size Subarray Sum, Minimum Window Substring.

StatusCollected
Notes2 solved

A window that grows and shrinks instead of staying a fixed size — expand the right edge until some condition is satisfied, then shrink the left edge as far as possible while it still holds.

int minSubArrayLen(int target, int *nums, int n) {
      int left = 0, sum = 0, best = INT_MAX;
      for (int right = 0; right < n; right++) {
          sum += nums[right];
          while (sum >= target) {
              int len = right - left + 1;
              if (len < best) best = len;
              sum -= nums[left];
              left++;
          }
      }
      return best == INT_MAX ? 0 : best;
  }

Minimum Window Substring is the harder version of the same shape, using a have/need pair of counters instead of a running sum: need records what the target string requires, have tracks how much of that is currently satisfied inside the window. Two details that actually mattered — guard the need count before incrementing have (only count a character if it's one the target actually needs), and check == 0 before decrementing on the shrink side, or the counts drift negative and the window looks satisfied when it isn't.

Notes from readers

Comments — via GitHub