Questions about stretches of a sequence, such as the busiest five minutes or the longest run without a repeat, tempt you to re-examine every stretch from scratch. A sliding window avoids that by reusing what the previous stretch already computed.
A window is a contiguous range of an array or string, described by a left and a right index. A sliding window algorithm moves the window along the data and keeps a summary of what is inside, such as a sum or a count per value. When the window moves, the summary is updated by the items that entered and left, not recomputed from the whole range.
There are two kinds, and the choice depends on whether the window length is given.
Kind
The window
Rule
Example
Fixed
Always k items
Move right by one: add the new item, drop the oldest
Total of every 5-minute window
Variable
Grows and shrinks
Expand right each step; move left while the window is invalid or while it is still good enough
Longest stretch with no repeat
Fixed
The windowAlways k items
RuleMove right by one: add the new item, drop the oldest
ExampleTotal of every 5-minute window
Variable
The windowGrows and shrinks
RuleExpand right each step; move left while the window is invalid or while it is still good enough
ExampleLongest stretch with no repeat
A window needs a property that you can maintain cheaply as items enter and leave: a sum, a count of distinct values, the last position of each value. Finding the maximum of a window is harder, because a leaving item may have been the maximum. That case has its own chapter on monotonic stacks.
A fixed window, in code
The function below returns the sum of every window of k items. It adds the new item at each step and, once the window is full, subtracts the item that just left.
ts
// Sum of every window of k items: add the new one, drop the old one.exportfunction windowSums(xs: number[], k: number): number[] {
const out: number[] = []
let sum = 0for (let i = 0; i < xs.length; i++) {
sum += xs[i]
if (i >= k) sum -= xs[i - k]
if (i >= k - 1) out.push(sum)
}
return out
}
The summary is the single variable sum. The cost per slide is two operations however large k is. The brute force, which sums each window from scratch, costs k operations per slide, so the sliding version is faster by a factor of about k / 2.
A variable window and why it is O(n)
A variable window has two indices that both only move right. The right index expands the window by one item each step. While the window satisfies a condition, the left index moves to shrink it. The function below finds the length of the shortest stretch whose sum reaches a target, and counts its steps.
ts
// Shortest stretch with sum >= target (non-negative values).// Returns its length (0 if none) and the steps taken.exportfunction shortestAtLeast(xs: number[], target: number) {
let left = 0let sum = 0let best = 0let steps = 0for (let right = 0; right < xs.length; right++) {
sum += xs[right]
steps++
while (sum >= target) {
const len = right - left + 1if (best === 0 || len < best) best = len
sum -= xs[left++]
steps++
}
}
return { best, steps }
}
There is a loop inside a loop, which looks quadratic. It is not. The left index never moves backwards, so over the whole run it moves at most n times, and the right index moves exactly n times. Each item enters the window once and leaves it at most once. The total number of steps is at most 2n, and the run below shows it.
n = 1000: length 13, 1988 steps, 2n = 2000
n = 10000: length 13, 19988 steps, 2n = 20000
A repeating list of 1 to 5; the steps stay under 2n
That argument holds whenever the inner loop moves an index that never goes back. If the inner loop restarted from zero, the cost would be quadratic again.
When negatives break it
The shrinking rule in the code above rests on one assumption: removing an item cannot raise the sum. That holds when every value is zero or more. With negative values it fails, because dropping a negative item from the left raises the sum, and a longer window might be better than the one you just gave up on.
The failure is easy to find by running both methods against each other. Trying every list of three or four values between -3 and 3 for a target of 3 turns up the first disagreement, and it is small.
ts
import { shortestAtLeast } from'./windows.ts'function brute(xs: number[], target: number): number {
let best = 0for (let i = 0; i < xs.length; i++) {
let sum = 0for (let j = i; j < xs.length; j++) {
sum += xs[j]
const len = j - i + 1if (sum >= target && (best === 0 || len < best)) best = len
}
}
return best
}
const xs = [-3, 3, -3]
console.log(`window method: ${shortestAtLeast(xs, 3).best}`)
console.log(`brute force: ${brute(xs, 3)}`)
text
window method: 0
brute force: 1
The window method misses the single item 3 in the list -3, 3, -3
The window method adds -3, then 3, then -3. The sum never reaches 3, so it never shrinks the window, and it never considers the stretch that holds only the 3. With negatives you need a different tool: the prefix sum chapter counts stretches with a given total, and that still works when values are negative. Learn to ask the question first: can values be negative? If yes, do not reach for a shrinking window.
Why is a variable window O(n) even though it has a loop inside a loop?
Both indices only move forward. Each item enters once and leaves at most once, so there are at most 2n steps.
What assumption does shrinking a window for "sum at least target" rely on?
That all values are non-negative, so removing an item can never raise the sum.
windowSums([4, 1, 6, 2], 3) returns two sums. How is the second one found from the first?
The first window is 4 + 1 + 6 = 11. The slide adds the entering 2 and subtracts the leaving 4, so the second is 11 + 2 - 4 = 9.
One addition and one subtraction per slide, whatever k is. The function returns [11, 9].
Part 2 · A five-minute average of server load
The problem
A monitoring service records how many requests a server handled in each minute of the day. The dashboard shows the total and average for every five-minute window, and highlights the busiest one. That is a fixed window: the length is given, and the summary is the sum.
The brute force adds up five numbers for each window. A better way keeps the total of the current window and, when the window slides one minute to the right, adds the new minute and subtracts the minute that dropped out. Averages come from dividing the total by k at the end, so the algorithm itself works with integers only, which avoids floating point drift from adding and subtracting fractions.
Animated sceneA 3-minute window over request counts0:18
The first window is full: sum 40
Read it as steps
The window sum changes by one add and one subtract per slide
Each slide changes the total by the difference between the item that entered and the one that left. The busiest window here covers minutes 3 to 7, counting from minute 0, with 44 requests.
The code and its tests
ts
// Requests per minute in; the total of every k-minute window out,// plus where the busiest window starts. Averages are total / k.exportfunction loadWindows(perMinute: number[], k: number) {
const totals: number[] = []
let sum = 0let busiest = -1for (let i = 0; i < perMinute.length; i++) {
sum += perMinute[i]
if (i >= k) sum -= perMinute[i - k]
if (i < k - 1) continue
totals.push(sum)
const last = totals.length - 1if (busiest < 0 || sum > totals[busiest]) busiest = last
}
return { totals, busiest }
}
The function returns every window total and the index of the first window with the highest total. The condition i < k - 1 skips the first k - 1 positions, where the window is not yet full. When k is larger than the data there are no full windows, so the result is empty.
✔ totals of every 3-minute window (1.0855ms)
✔ a window longer than the data gives nothing (0.1173ms)
✔ k = 1 returns the values (0.0923ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
One test run on this machine; the times vary
Comparing with recomputing
To show what the sliding version saves, the next function does the obvious work and counts additions. The run uses a full day of 1,440 minutes, with a window of 5 and then 60 minutes, and checks that both methods give the same totals.
ts
// Recomputes each window from scratch; counts the additions.exportfunction naiveTotals(perMinute: number[], k: number) {
const totals: number[] = []
let adds = 0for (let start = 0; start + k <= perMinute.length; start++) {
let sum = 0for (let i = start; i < start + k; i++) {
sum += perMinute[i]
adds++
}
totals.push(sum)
}
return { totals, adds }
}
ts
import { loadWindows, naiveTotals } from'./load.ts'const day = 24 * 60const data = Array.from({ length: day }, (_, i) => 100 + (i * 37) % 23)
for (const k of [5, 60]) {
const slow = naiveTotals(data, k)
const fast = loadWindows(data, k)
const same = slow.totals.join() === fast.totals.join()
const windows = fast.totals.length
console.log(`k = ${k}: ${windows} windows, same totals: ${same}`)
console.log(` recompute each: ${slow.adds} additions`)
console.log(` slide: ${day + (day - k)} additions and subtractions`)
}
const { totals, busiest } = loadWindows(data, 5)
console.log(`busiest 5-minute window starts at minute ${busiest}`)
console.log(`its average: ${totals[busiest] / 5} requests per minute`)
text
k = 5: 1436 windows, same totals: true
recompute each: 7180 additions
slide: 2875 additions and subtractions
k = 60: 1381 windows, same totals: true
recompute each: 82860 additions
slide: 2820 additions and subtractions
busiest 5-minute window starts at minute 18
its average: 113.2 requests per minute
Request counts follow a fixed pattern, so the run repeats exactly
For a 5-minute window the sliding version does about 2.5 times fewer operations. For a 60-minute window it does about 29 times fewer, because its cost stays near 2n while the recompute cost grows with k. The average of the busiest window is the total divided by k: 113.2 requests per minute.
Three details are easy to miss. First, the data must have one entry for every minute, including minutes with no requests, which should be zero; if the log only lists minutes that had traffic, fill the gaps before sliding, or the windows will cover the wrong time. Second, when two windows tie for the highest total, the function reports the first because it uses a strict comparison. Third, the same loop works for any summary that you can add and remove, such as a count of minutes above a limit: add one when the entering minute is above it and subtract one when the leaving minute was.
Why compute totals and divide at the end?
Adding and subtracting totals is exact in integers. Repeatedly adjusting fractional averages can accumulate rounding error.
For n = 1,440 and k = 60, about how many operations do the two methods take?
Recomputing each window takes 82,860 additions. Sliding takes 2,820 additions and subtractions, as in the run above.
A version of loadWindows records a total when i >= k instead of skipping while i < k - 1. What does it return for the minutes [12, 8, 20, 5] with k = 3?
It returns [33] instead of [40, 33]. The first full window ends at index k - 1 = 2, and the changed condition skips it.
The subtraction still starts at i = k, so every later total is right. Only the first window goes missing, which is why the k = 1 and short-data tests are worth keeping.
Part 3 · The shortest stretch to reach a target
The problem
A solar plant logs its output for every hour of the day in kilowatt-hours. The operator wants the shortest run of consecutive hours whose total output reaches a target, to plan the best time for a heavy job. A day with a zero for the hours before sunrise is typical.
This is a variable window with a shrinking rule. Expand the right edge one hour at a time and add that hour to the sum. As soon as the sum reaches the target, the window is a candidate. Record its length, then move the left edge forward, subtracting each hour, for as long as the sum still reaches the target. Each shorter window found on the way is a better candidate.
The reason the algorithm is correct is the non-negativity from the introduction. For a fixed right edge, the shortest valid window ends at that edge and starts at the largest left position that still reaches the target. Shrinking from the left finds it. And once the sum from left to right reaches the target, any window that starts at left and ends further right is longer than the one just recorded, so that left position is finished and can be dropped.
The code
ts
// Shortest run of hours whose output reaches target (kWh >= 0).// Returns [firstHour, lastHour], or null if the day never reaches it.exportfunction shortestRun(
hours: number[],
target: number,
log = false,
): [number, number] | null {
let left = 0let sum = 0let best: [number, number] | null = nullfor (let right = 0; right < hours.length; right++) {
sum += hours[right]
while (sum >= target) {
if (log) console.log(`hours ${left}-${right} reach ${sum}`)
const shorter = !best || right - left < best[1] - best[0]
if (shorter) best = [left, right]
sum -= hours[left++]
}
}
return best
}
The loop condition is while, not if, because dropping one hour may still leave the sum at or above the target. When the log flag is on, it prints each window that reaches the target. Here is a run over a day of ten readings with a target of 30.
Every window that reached 30 while the left edge advanced
Reading the trace and testing
The first window to reach 30 is hours 0 to 5. The left edge then moves right while the sum stays at or above 30, giving hours 1 to 5, 2 to 5 and 3 to 5. Hours 3 to 5 produce 35, and dropping hour 3 would leave 26, so the loop stops. The window then grows on the right and the next valid windows are hours 4 to 6 and 5 to 7, each with three hours. The first three-hour window is kept because later ones are not shorter.
ts
import test from'node:test'import assert from'node:assert/strict'import { shortestRun } from'./solar.ts'
test('one hour can be enough', () => {
assert.deepEqual(shortestRun([1, 9, 2], 9), [1, 1])
})
test('the whole day may be needed', () => {
assert.deepEqual(shortestRun([2, 2, 2], 6), [0, 2])
})
test('target never reached', () => {
assert.equal(shortestRun([1, 1, 1], 4), null)
})
test('zero-output hours are fine', () => {
assert.deepEqual(shortestRun([0, 0, 5, 0], 5), [2, 2])
})
text
✔ one hour can be enough (0.8931ms)
✔ the whole day may be needed (0.0932ms)
✔ target never reached (0.0993ms)
✔ zero-output hours are fine (0.0784ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
One test run on this machine; the times vary
A stress test also compared the function with a brute force over 3,000 random days of up to eight non-negative readings and targets from 1 to 15. It printed 3000 random days agree with the brute force.
Notice that the stress targets start at 1. The function assumes a positive target. With a target of 0, even an empty stretch is enough, and the shrinking loop runs the left edge past the right edge: shortestRun([0, 2, 5], 0, true) printed windows such as hours 1-0 and returned [ 1, 0 ], a range that holds no hour at all. Reject a target of 0 or less before the loop, or say what it should mean, rather than let the window run past its own right edge.
The cost is O(n) time, using the same argument as before, and O(1) space. Related on LeetCode: Minimum Size Subarray Sum is this problem.
Why is the shrinking loop a while and not an if?
After removing one item the sum can still reach the target, so the left edge may need to move several times.
What goes wrong if some hourly readings are negative?
Removing a negative item raises the sum, so the shrinking rule can discard stretches it should have tried. The introduction shows a failing case.
What does the function return when the day never reaches the target?
null, because no window ever sets the best value. A target of 0 or less is a different problem: check it before the loop.
Part 4 · The longest run of unique songs
The problem
A music app logs the songs a listener played in order. The product team wants the longest stretch in which no song repeated, as a measure of how varied a session was. The window is variable, and the condition is that all items inside it are different.
The slow way keeps a set of songs in the window. When a song arrives that is already in the set, the left edge moves right one step at a time, removing songs, until the duplicate is gone. That works in O(n), but the left edge moves in small steps.
A faster way stores, for each song, the position where it was last played. When a song arrives whose last position is inside the current window, the left edge can jump straight to one position after that earlier copy. Nothing between the old left edge and that spot can be part of a valid window ending at the new item, so there is no need to walk through them.
The code
ts
// Longest stretch of a play log with no song repeated.exportfunction longestUnique(songs: string[]): number {
const lastAt = new Map<string, number>()
let left = 0let best = 0for (let right = 0; right < songs.length; right++) {
const at = lastAt.get(songs[right])
if (at !== undefined && at >= left) left = at + 1
lastAt.set(songs[right], right)
best = Math.max(best, right - left + 1)
}
return best
}
The check at >= left matters. The map keeps the last position of every song ever seen, including ones that left the window long ago. A copy that is already to the left of the window is not a duplicate within it, and ignoring that check would move the left edge backwards.
The window is the range from left to right, so its length is right - left + 1. The map is updated after the check, so that the new position replaces the older one.
✔ empty log (0.5875ms)
✔ all songs equal (0.1061ms)
✔ all songs different (0.0861ms)
✔ the left edge jumps past the earlier copy (0.1394ms)
✔ an old copy outside the window is ignored (0.1036ms)
ℹ tests 5
ℹ pass 5
ℹ fail 0
One test run on this machine; the times vary
The two cases that expose most mistakes are the last two tests. In the fourth, a repeat of b moves the left edge past the first b. In the fifth, an old a sits outside the window when the new a arrives, and must be ignored. A brute force that tries every start and extends until a repeat is the reference for a random check.
ts
exportfunction longestUniqueBrute(songs: string[]): number {
let best = 0for (let i = 0; i < songs.length; i++) {
const seen = new Set<string>()
for (let j = i; j < songs.length && !seen.has(songs[j]); j++) {
seen.add(songs[j])
best = Math.max(best, j - i + 1)
}
}
return best
}
Trace the log a, b, c, b, a, d to see the jump. The window grows to a, b, c. When the second b arrives, its last position is 1, which is inside the window, so left jumps to 2 and the window is c, b. The next a was last seen at position 0, before left, so it is ignored and the window grows to c, b, a. Then d arrives and the window is c, b, a, d, of length 4. The set-based version would have removed a, b and c one at a time to reach the same place. The map version sets the left edge in one step, though both are O(n) overall. Space is the number of distinct songs in the log, not the number of plays.
Why does the code check that the last position is at least left?
A copy to the left of the window is not inside it. Without the check the left edge could move backwards.
What is the time and space cost?
O(n) time. Space is O(d) where d is the number of distinct songs, because the map holds one entry for each.
Delete the at >= left check. What does the function return for the log a, b, b, a, and why?
It returns 3 instead of 2. At the second b the left edge moves to 2. At the second a the old position 0 sends it back to 1, so the window b, b, a is counted although it holds b twice.
Part 5 · At most two vehicle classes
The problem
A toll plaza logs the class of each vehicle that passes: car, bus, van and so on. An analyst wants the longest stretch of the log in which at most k different classes appear. The condition is no longer "all different" but "few different", and the summary has to track how many of each class are inside the window.
Use a Map from class to count. When the right edge adds a class, increase its count. If the map now holds more than k keys, the window is invalid, so the left edge moves right and decreases the count of the class it leaves. When a count reaches zero, the key must be deleted, because the number of keys is what the condition measures. A count of zero left in the map would make the window look as if it still had that class.
Animated sceneAt most two classes in a toll log0:27
Watch for the third class arriving and the left edge moving until one count hits zero
Read it as steps
A third class arrives and the left edge moves until a class leaves
The scene shows the three moments that matter: a class is added, the map exceeds two keys, and the left edge advances until one key disappears. The longest stretch is 4, from the second bus to the last car.
The code
ts
// Longest stretch of a toll log with at most k distinct classes.exportfunction longestAtMost(classes: string[], k: number): number {
const count = new Map<string, number>()
let left = 0let best = 0for (let right = 0; right < classes.length; right++) {
count.set(classes[right], (count.get(classes[right]) ?? 0) + 1)
while (count.size > k) {
const c = classes[left++]
const rest = (count.get(c) as number) - 1if (rest === 0) count.delete(c)
else count.set(c, rest)
}
best = Math.max(best, right - left + 1)
}
return best
}
The structure is the same as the shortest-stretch lesson. A while loop restores validity after each expansion. The best length is recorded after the loop, when the window is valid, so that an invalid window is never counted. Deleting a key when its count drops to zero is what keeps the number of keys equal to the number of classes inside the window.
Run through the whole log with k = 2 and you see the window stretch to three items, shrink to two when the van arrives, and end on bus, bus, car, car as the longest.
✔ k = 1 finds the longest single-class run (0.5457ms)
✔ k = 2 allows two classes (0.0908ms)
✔ k = 3 covers the whole log (0.066ms)
✔ k = 0 and an empty log (0.066ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
One test run on this machine; the times vary
The log has three classes. With k = 1 the longest single-class run is two. With k = 2 it is four. With k = 3 the whole log of eight is valid. A value of k = 0 allows no class at all, so the answer is zero, as it is for an empty log.
The time is O(n), since each item enters and leaves once, and the map stays within k + 1 keys, so the extra space is O(k). Related on LeetCode: Fruit Into Baskets is this problem with k fixed at 2, and Longest Repeating Character Replacement uses the same window with a different validity condition: the window length minus its most common letter must be at most the allowed number of changes.
Why must a key be deleted when its count reaches zero?
The condition counts keys in the map. A key with count zero would be counted as a class that is still present.
With k = 2, what does longestAtMost return for bus, van, bus, car, car, car?
It returns 4. The window grows to bus, van, bus. When car arrives the left edge drops the first bus and the van, leaving bus, car, which then grows to bus, car, car, car.
The map never holds more than k + 1 = 3 keys, so the extra space is O(k).
Why is best updated after the while loop and not inside it?
Inside the loop the window may be invalid. After it the window satisfies the condition.
Part 6 · The smallest window that covers a keyword list
The problem
A support team reads chat transcripts and wants to find the shortest stretch of words that mentions every keyword on a list, such as refund and order, to build a short summary. If a keyword is listed twice, the stretch must contain it twice. This is the opposite shape from the last lesson: the window must contain enough of something, so the left edge shrinks while the window is still good.
Keep a table want of how many copies of each keyword are needed, and a table have of how many are in the window. Keep one more number, missing, the count of keyword copies still needed. When a keyword enters and its count in have is still within what is wanted, missing goes down by one. When missing reaches zero the window covers the list.
Then shrink. While the window still covers the list, record it if it is shorter than the best, then move the left edge. If the word that leaves is a keyword, reduce its count, and if that drops below what is wanted, missing goes up and the shrinking stops. Words that are not keywords can leave freely.
The code
ts
// Shortest stretch of words holding every keyword (with counts).exportfunction smallestCover(
words: string[],
need: string[],
log = false,
): [number, number] | null {
const want = new Map<string, number>()
for (const w of need) want.set(w, (want.get(w) ?? 0) + 1)
const have = new Map<string, number>()
let missing = need.length // keyword copies still neededlet left = 0let best: [number, number] | null = nullfor (let right = 0; right < words.length; right++) {
const w = words[right]
if (want.has(w)) {
have.set(w, (have.get(w) ?? 0) + 1)
if (have.get(w)! <= want.get(w)!) missing--
}
while (need.length > 0 && missing === 0) {
if (log) console.log(`covered: ${left}-${right}`)
const size = right - left
if (!best || size < best[1] - best[0]) best = [left, right]
const out = words[left++]
if (!want.has(out)) continue
have.set(out, have.get(out)! - 1)
if (have.get(out)! < want.get(out)!) missing++
}
}
return best
}
Tracking missing as one number makes the check for "does the window cover the list" constant time. The alternative, comparing two tables after every step, would cost the size of the keyword list each time.
Watching the windows
ts
import { smallestCover } from'./cover.ts'const chat = 'sorry refund order late refund please order help'
.split(' ')
console.log(smallestCover(chat, ['refund', 'order'], true))
console.log(smallestCover(chat, ['refund', 'refund', 'help'], true))
console.log(smallestCover(chat, ['refund', 'cancel']))
Windows printed at each shrink for three keyword lists
For the keywords refund and order the first cover is words 0 to 2, which still holds when sorry is dropped, giving words 1 to 2 as the best. The second list needs refund twice and help once. The only cover that includes both refunds and the help is words 1 to 7. The third list contains a keyword, cancel, that never appears, so the result is null.
✔ finds the shortest cover (1.253ms)
✔ repeated keywords need repeated copies (0.1411ms)
✔ a missing keyword gives null (0.1383ms)
✔ no keywords needed: nothing to cover (0.0939ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
One test run on this machine; the times vary
A random comparison with a brute force that tries every range also agreed on 3,000 cases, using short chats over three words. The cost is O(n + m) time for n words and m keywords, and O(m) space.
The fixed-length relatives of this problem use the same two tables. To ask whether a window of exactly the pattern length holds the same letters as a pattern, keep have for the window and compare it with want, sliding one letter at a time. The fixed version is O(n) as well, because each letter enters and leaves the window once and each step updates one count. Words that are not on the keyword list never touch the tables: on the way in the function only counts words that want holds, and on the way out the shrinking loop skips them with continue.
Why track missing instead of comparing the two tables?
One number answers the coverage question in constant time. Comparing tables costs the size of the keyword list at every step.
When does the shrinking loop stop?
When removing the word at the left edge would leave a keyword short, which makes missing positive again.
For the same chat and the keywords order and help, what does smallestCover return?
[6, 7]. The window first covers both keywords when help arrives, as words 0 to 7. The first order can leave because the order at word 6 is still inside, and shrinking stops only when that one would go. The shortest cover is words 6 and 7.
Part 7 · A repeated sensor signature
The problem
A factory sensor emits one digit per reading. A fixed-length pattern of readings, a signature, that appears twice in the stream may point to a repeating fault. The task is to find every signature of length L that appears at least twice. The window length is fixed, and the summary is the text of the window itself.
The direct way slices each window into a string and puts it in a Set. If the string is already there, it is a repeat. Slicing costs O(L) per window, so the total is O(nL), and the set keeps up to n strings.
ts
// Every length-L signature that appears at least twice, by set.exportfunction repeatedBySet(s: string, L: number): string[] {
const seen = new Set<string>()
const again = new Set<string>()
for (let i = 0; i + L <= s.length; i++) {
const key = s.slice(i, i + L)
if (seen.has(key)) again.add(key)
else seen.add(key)
}
return [...again].sort()
}
A rolling hash
A hash is a number computed from a string so that equal strings always give equal numbers. A rolling hash can be updated in constant time as the window slides: remove the contribution of the digit that leaves, shift the rest one place, add the digit that enters. For digits it is the window read as a decimal number, reduced modulo a chosen number mod so that it stays small.
Two different windows can have the same hash, which is called a collision. So a hash match is only a hint. The code keeps the start positions seen for each hash value, and before it counts a repeat it compares the actual text of the two windows. The comparison costs O(L), but it only runs when the hash matches, so the code slices the window only then. When collisions are rare the hash version does O(1) work for most windows instead of O(L).
ts
// The same answer with a rolling hash. A hash match is only a hint,// so the text is compared before it counts. Digits only.exportfunction repeatedByHash(s: string, L: number, mod: number) {
const starts = new Map<number, number[]>()
const again = new Set<string>()
let falseHits = 0let h = 0let top = 1// 10^(L-1) mod `mod`for (let i = 1; i < L; i++) top = (top * 10) % mod
for (let i = 0; i < s.length; i++) {
if (i >= L) {
const out = ((s.charCodeAt(i - L) - 48) * top) % mod
h = (h - out + mod) % mod
}
h = (h * 10 + (s.charCodeAt(i) - 48)) % mod
if (i < L - 1) continueconst at = i - L + 1const prior = starts.get(h) ?? []
if (prior.length) {
const key = s.slice(at, i + 1) // sliced only on a hash matchif (prior.some((p) => s.slice(p, p + L) === key)) again.add(key)
else falseHits++
}
prior.push(at)
starts.set(h, prior)
}
return { repeats: [...again].sort(), falseHits }
}
Counting collisions
The run below builds 3,000 random digits with a seeded generator and looks for signatures of length 5. It runs the set version and then the hash version with three values of mod, and counts how many hash matches the text comparison rejected.
ts
import { mulberry32 } from'./rng.ts'import { repeatedBySet, repeatedByHash } from'./signatures.ts'const rand = mulberry32(8)
let stream = ''for (let i = 0; i < 3000; i++) stream += Math.floor(rand() * 10)
const L = 5const want = repeatedBySet(stream, L)
console.log(`stream of ${stream.length} readings, signatures of ${L}`)
console.log(`set: ${want.length} repeated signatures`)
for (const mod of [101, 10_007, 1_000_003]) {
const { repeats, falseHits } = repeatedByHash(stream, L, mod)
const same = repeats.join() === want.join()
console.log(`mod ${mod}: ${repeats.length} repeated, same: ${same},`
+ ` ${falseHits} hash matches rejected`)
}
text
stream of 3000 readings, signatures of 5
set: 50 repeated signatures
mod 101: 50 repeated, same: true, 2845 hash matches rejected
mod 10007: 50 repeated, same: true, 322 hash matches rejected
mod 1000003: 50 repeated, same: true, 0 hash matches rejected
The three hash runs find the same 50 repeats as the set
With mod 101 there are 2,845 false matches, since only 101 hash values exist for 2,996 windows, and the answer is still right because every match is compared. With 10,007 there are 322 false matches. With 10,00,003, larger than the 1,00,000 possible five-digit signatures, the hash is exact for digit strings and there are none. A real rolling hash for general text uses a larger base and modulus, and still needs the comparison to be safe.
ts
import test from'node:test'import assert from'node:assert/strict'import { repeatedBySet, repeatedByHash } from'./signatures.ts'
test('finds a signature that appears twice', () => {
assert.deepEqual(repeatedBySet('1234512345', 5), ['12345'])
})
test('overlapping repeats count', () => {
assert.deepEqual(repeatedBySet('1111111', 3), ['111'])
})
test('the hash version agrees even with a tiny modulus', () => {
const s = '90817263549081726354'
assert.deepEqual(repeatedByHash(s, 4, 7).repeats, repeatedBySet(s, 4))
})
test('too short for any window', () => {
assert.deepEqual(repeatedBySet('123', 5), [])
})
text
✔ finds a signature that appears twice (0.8818ms)
✔ overlapping repeats count (0.1211ms)
✔ the hash version agrees even with a tiny modulus (0.2119ms)
✔ too short for any window (0.093ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
One test run on this machine; the times vary
The tests include a modulus of 7, so tiny that almost every match is a collision, and the answer still agrees with the set. Related on LeetCode: Repeated DNA Sequences is this problem with letters, and Contains Duplicate II uses a window of recent items to look for a repeat close by.
Term
Meaning
Window
A contiguous range of a sequence, from a left index to a right index
Fixed window
A window whose length is given and stays the same
Variable window
A window that grows on the right and shrinks on the left
Rolling hash
A hash that is updated in constant time when the window slides
Collision
Two different values that have the same hash
Signature
A fixed-length pattern of readings
Why must a hash match be confirmed by comparing the text?
Different windows can share a hash. Only the comparison proves they are equal.
Why did the false matches drop to zero for a modulus of 10,00,003?
Five-digit signatures have at most 1,00,000 values, which is below the modulus, so each signature has its own hash.
You look for signatures of length 3 with a modulus of 1,000. Will the text comparison ever reject a match?
No. A three-digit window read as a number is 0 to 999, all below 1,000, so the hash is the value itself and different windows never share it.
A run on the same 3,000-digit stream with L = 3 and mod 1,000 rejected 0 matches and found the same repeats as the set.