DSAVisualiseData Structures & Algorithms Studio
Strings & Compression Easy

Rolling Hash (Incremental)

A fixed-width polynomial hash can be updated in constant time by removing the outgoing character and appending the incoming one.

Trace input

Bounded JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

Source scenarios

Complexity

BestO(M + N) for all window hashes
AverageO(M + N) for all window hashes
WorstO(M + N) for all window hashes
SpaceO(N - M + 1) output hashes

Array state

Follow the active comparisons and writes.

Live snapshot

Current operation

Trace state
Ready to explore
Source behavior & common mistakes

Hash the first window with the documented polynomial formula, then apply the source's nextHash arithmetic to every following window.

  • The fixed source radix is R=31; RM is computed as R^(M-1) using signed Java int multiplication and remainder.
  • nextHash removes t[from-1] × RM, multiplies by R, then adds t[from+M-1].
  • Java int multiplication and addition overflow before `% Q`; the source does not normalize negative remainders into [0,Q).
  • The source Javadoc permits from == text.length - M; the upstream tests allocate only size-M hashes and stop one window early.
  • The source implements nextHash only; the lesson seeds the first window from its documented polynomial formula.
  • Java char indexing and String.length operate on UTF-16 code units, not Unicode code points.

Algorithm code

Java
IncrementalHash.javaStep linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1