Sliding Window
A sliding window maintains a contiguous slice of an array as two indices move. TypeScript's job is to type the source, the window, and the aggregate so the slice is not an any[].
Detailed Explanation
The runtime technique is a pair of indices, start and end, that describe items[start..end). You expand end to include more, shrink start to drop from the left, and update a running aggregate so you do not re-scan the slice. That is JavaScript. The types are about what items is and what you emit per window.
A generic form looks like this:
function eachWindow<T>(
items: readonly T[],
size: number,
visit: (window: readonly T[]) => void,
): void
window should stay readonly T[], not T[], if the visitor is not allowed to mutate the source. If you pass a live view (the same array plus indices) instead of slice, the type readonly T[] is a lie unless you copy. Be honest: either slice (allocating, typed T[]) or pass { items, start, end } so the visitor indexes on purpose.
Aggregates need their own type. A window that tracks character counts is Map<string, number> or Record<string, number>. A window that tracks the max is T plus a constraint (T extends number). Do not store the aggregate as any. The whole point of writing the algorithm in TypeScript is that the running state has a type you can refactor.
Fixed-size vs variable-size windows have the same typing story. The size parameter is a number; the type system will not prove that end - start === size. If you want a tuple of length 3, you cannot get it from a dynamic size without a lot of overloads (size: 1, size: 2, …). Overload the public API for the two or three sizes you actually use, and keep the implementation on T[].
Empty inputs and size <= 0 are runtime checks. Type them as early returns, not as never. The compiler will not exclude them.
See the JavaScript sliding-window page for the standard problems (longest substring, minimum subarray, anagrams). Here, keep the window's element type and the aggregate type visible in the signature.
Code Examples
1. Fixed-size windows as readonly slices.
// 1. Fixed-size windows as readonly slices.
function eachWindow<T>(
items: readonly T[],
size: number,
visit: (window: readonly T[]) => void,
): void {
if (size <= 0) return;
for (let start = 0; start + size <= items.length; start++) {
visit(items.slice(start, start + size));
}
}
eachWindow([1, 2, 3, 4], 2, (w) => {
console.log(w);
});2. Variable window with a typed aggregate (max sum of a subarray of length k).
// 2. Variable window with a typed aggregate (max sum of a subarray of length k).
function maxSum(nums: readonly number[], k: number): number | undefined {
if (k <= 0 || nums.length < k) return undefined;
let sum = 0;
for (let i = 0; i < k; i++) sum += nums[i];
let best = sum;
for (let end = k; end < nums.length; end++) {
sum += nums[end] - nums[end - k];
if (sum > best) best = sum;
}
return best;
}
console.log(maxSum([2, 1, 5, 1, 3, 2], 3)); // 93. A window state typed as a Map, not any.
// 3. A window state typed as a Map, not any.
function longestUnique(s: string): number {
const last = new Map<string, number>();
let start = 0;
let best = 0;
for (let end = 0; end < s.length; end++) {
const ch = s[end];
const prev = last.get(ch);
if (prev !== undefined && prev >= start) start = prev + 1;
last.set(ch, end);
const len = end - start + 1;
if (len > best) best = len;
}
return best;
}Common Gotchas
`slice` allocates a new array per window
if the visitor only needs indices, pass `start` and `end` and keep the type on `items`.
A dynamic `size` cannot become a tuple type
`[T, T, T]` is for a literal 3. Do not assert a slice to a tuple unless you just checked `length`.
Aggregates should be generic or constrained
`Map<K, number>` / `T extends number` beat `any` for the running state.
`noUncheckedIndexedAccess` makes `nums[i]` possibly undefined
guard `i` or use a loop that iterates values.