Sikau

Algorithms · Day 7 · about 35 min

Sliding window

Best subarray or substring in one pass by growing and shrinking a window.

The busiest hour

Which 60 consecutive minutes had the most orders? Recomputing every window from scratch is O(n·k). A sliding window adds the item entering on the right and removes the one leaving on the left: O(n).

Fixed and variable windows

function busiest(ordersPerMinute, k) {
  let sum = 0, best = -Infinity, bestStart = 0;
  for (let i = 0; i < ordersPerMinute.length; i++) {
    sum += ordersPerMinute[i];
    if (i >= k) sum -= ordersPerMinute[i - k];
    if (i >= k - 1 && sum > best) { best = sum; bestStart = i - k + 1; }
  }
  return { best, bestStart };
}
console.log(busiest([1, 4, 2, 0, 7, 3, 1, 9], 3));

// Variable window: the longest stretch with at most 'budget' total.
function longestWithin(costs, budget) {
  let left = 0, sum = 0, best = 0;
  for (let right = 0; right < costs.length; right++) {
    sum += costs[right];
    while (sum > budget) sum -= costs[left++];
    best = Math.max(best, right - left + 1);
  }
  return best;
}
console.log(longestWithin([2, 1, 5, 1, 1, 1, 3], 6));

The rest of this lesson

  • Variable windowsexplain
  • Spotting window problemsexplain
  • Why O(n), with a while inside a for?predict
  • Window or not?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Algorithms