Module 1 · Drill 2 · five reps

Sliding window pack

Five sliding-window classics. Three are fixed-size, two are variable-size. After this drill you should be able to articulate, mid-interview, which flavor a problem calls for and why.

1 — Max sum of size-k window (fixed)

2 — Longest substring without repeating characters (variable)

3 — Smallest subarray with sum ≥ target (variable)

4 — Permutation in string (fixed window + frequency map)

5 — Longest substring with at most K distinct characters (variable)

Solutions

1 — Max sum of length-k window

def max_sum_k(arr, k):
    s = sum(arr[:k])
    best = s
    for i in range(k, len(arr)):
        s += arr[i] - arr[i - k]   # add new, drop old
        if s > best: best = s
    return best
  
function maxSumK(arr, k) {
  let s = 0;
  for (let i = 0; i < k; i++) s += arr[i];
  let best = s;
  for (let i = k; i < arr.length; i++) {
    s += arr[i] - arr[i - k];
    if (s > best) best = s;
  }
  return best;
}
  
function maxSumK(arr: number[], k: number): number {
  let s = 0;
  for (let i = 0; i < k; i++) s += arr[i];
  let best = s;
  for (let i = k; i < arr.length; i++) {
    s += arr[i] - arr[i - k];
    if (s > best) best = s;
  }
  return best;
}
  
O(n) time, O(1) space. The window's contents change by exactly one in and one out per step — recompute the sum incrementally instead of rescanning.

2 — Longest substring without repeating characters

def longest_unique(s):
    seen = {}     # char -> most recent index
    left = best = 0
    for right, ch in enumerate(s):
        if ch in seen and seen[ch] >= left:
            left = seen[ch] + 1     # jump past previous occurrence
        seen[ch] = right
        if right - left + 1 > best: best = right - left + 1
    return best
  
function longestUnique(s) {
  const seen = new Map();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    if (seen.has(ch) && seen.get(ch) >= left) {
      left = seen.get(ch) + 1;
    }
    seen.set(ch, right);
    if (right - left + 1 > best) best = right - left + 1;
  }
  return best;
}
  
function longestUnique(s: string): number {
  const seen = new Map<string, number>();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    if (seen.has(ch) && seen.get(ch)! >= left) {
      left = seen.get(ch)! + 1;
    }
    seen.set(ch, right);
    if (right - left + 1 > best) best = right - left + 1;
  }
  return best;
}
  
O(n) time, O(min(n, alphabet)) space. The invariant: window has no repeats. When a duplicate appears, jump left past its previous occurrence — but only if that occurrence is still inside the window (the >= left check).

3 — Smallest subarray with sum ≥ target

def min_subarray(target, nums):
    left = 0
    s = 0
    best = float('inf')
    for right, x in enumerate(nums):
        s += x
        while s >= target:
            best = min(best, right - left + 1)
            s -= nums[left]
            left += 1
    return 0 if best == float('inf') else best
  
function minSubarray(target, nums) {
  let left = 0, s = 0, best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    s += nums[right];
    while (s >= target) {
      best = Math.min(best, right - left + 1);
      s -= nums[left++];
    }
  }
  return best === Infinity ? 0 : best;
}
  
function minSubarray(target: number, nums: number[]): number {
  let left = 0, s = 0, best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    s += nums[right];
    while (s >= target) {
      best = Math.min(best, right - left + 1);
      s -= nums[left++];
    }
  }
  return best === Infinity ? 0 : best;
}
  
O(n) time, O(1) space. Variable window. Expand right while sum < target; once sum ≥ target, contract from the left as far as possible while maintaining the invariant. Each pointer moves at most n times → O(n) total.

4 — Permutation in string

from collections import Counter

def has_permutation(s1, s2):
    if len(s1) > len(s2): return False
    need = Counter(s1)
    window = Counter(s2[:len(s1)])
    if window == need: return True
    for i in range(len(s1), len(s2)):
        window[s2[i]] += 1
        window[s2[i - len(s1)]] -= 1
        if window[s2[i - len(s1)]] == 0:
            del window[s2[i - len(s1)]]
        if window == need: return True
    return False
  
function hasPermutation(s1, s2) {
  if (s1.length > s2.length) return false;
  const need = {};
  for (const c of s1) need[c] = (need[c] || 0) + 1;
  const win = {};
  for (let i = 0; i < s1.length; i++) win[s2[i]] = (win[s2[i]] || 0) + 1;
  function eq() {
    const ks = new Set([...Object.keys(need), ...Object.keys(win)]);
    for (const k of ks) if ((need[k] || 0) !== (win[k] || 0)) return false;
    return true;
  }
  if (eq()) return true;
  for (let i = s1.length; i < s2.length; i++) {
    win[s2[i]] = (win[s2[i]] || 0) + 1;
    win[s2[i - s1.length]]--;
    if (eq()) return true;
  }
  return false;
}
  
function hasPermutation(s1: string, s2: string): boolean {
  if (s1.length > s2.length) return false;
  const need: Record<string, number> = {};
  for (const c of s1) need[c] = (need[c] || 0) + 1;
  const win: Record<string, number> = {};
  for (let i = 0; i < s1.length; i++) win[s2[i]] = (win[s2[i]] || 0) + 1;
  function eq(): boolean {
    const ks = new Set([...Object.keys(need), ...Object.keys(win)]);
    for (const k of ks) if ((need[k] || 0) !== (win[k] || 0)) return false;
    return true;
  }
  if (eq()) return true;
  for (let i = s1.length; i < s2.length; i++) {
    win[s2[i]] = (win[s2[i]] || 0) + 1;
    win[s2[i - s1.length]]--;
    if (eq()) return true;
  }
  return false;
}
  
O(n + m) time, O(alphabet) space. Fixed-size window of length |s1| over s2; compare frequency maps. Pro version: maintain a "matches" counter that increments/decrements as window edges change, so equality check is O(1) per step instead of O(alphabet) — turns the algorithm into a pure O(n + m) sweep.

5 — Longest substring with ≤ k distinct characters

def longest_k_distinct(s, k):
    counts = {}
    left = best = 0
    for right, ch in enumerate(s):
        counts[ch] = counts.get(ch, 0) + 1
        while len(counts) > k:
            counts[s[left]] -= 1
            if counts[s[left]] == 0:
                del counts[s[left]]
            left += 1
        if right - left + 1 > best: best = right - left + 1
    return best
  
function longestKDistinct(s, k) {
  const counts = new Map();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    counts.set(ch, (counts.get(ch) || 0) + 1);
    while (counts.size > k) {
      const lc = s[left];
      counts.set(lc, counts.get(lc) - 1);
      if (counts.get(lc) === 0) counts.delete(lc);
      left++;
    }
    if (right - left + 1 > best) best = right - left + 1;
  }
  return best;
}
  
function longestKDistinct(s: string, k: number): number {
  const counts = new Map<string, number>();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    counts.set(ch, (counts.get(ch) || 0) + 1);
    while (counts.size > k) {
      const lc = s[left];
      counts.set(lc, counts.get(lc)! - 1);
      if (counts.get(lc) === 0) counts.delete(lc);
      left++;
    }
    if (right - left + 1 > best) best = right - left + 1;
  }
  return best;
}
  
O(n) time, O(k) space. Variable window with the invariant "at most k distinct chars." When that breaks, contract left until it holds again. The map size is the count-of-distinct-chars in O(1).
Notebook prompt

For each of the five, write the invariant you maintained on the window. Example for #5: "the window contains at most k distinct characters." This invariant-naming habit will save you on every variable-window problem you ever see.