Workspace Z Algorithm
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Z Algorithm visualizer

Learn Z Algorithm with a step-by-step Strings visualizer, JavaScript source code and a worked example. Practice pattern matching.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 7Execution step
Reference example · JavaScript
Inspect reference input
"aabxaab"

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let z=Array(a.length).fill(0),l=0,r=0;
for(let i=1;
i<a.length;
i++){
if(i<=r)z[i]=Math.min(r-i+1,z[i-l]);
while(i+z[i]<a.length&&a[z[i]]===a[i+z[i]])z[i]++;
if(i+z[i]-1>r){
l=i;
r=i+z[i]-1
}
s("Extend prefix match",{
Array:[...a],Z:z,Bounds:[l,r]
},[i])
}
return z
};

Execution canvas

Active Changed
STEP 1

Extend prefix match

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Array7 items
Z7 items
Bounds2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Strings · Pattern matching

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

"aabxaab"

Execution steps

  1. Extend prefix match

Computed output

[
  0,
  1,
  0,
  0,
  3,
  1,
  0
]
JavaScript reference implementation
const solve = (a,s)=>{
  let z=Array(a.length).fill(0),l=0,r=0;
  for(let i=1;
  i<a.length;
  i++){
    if(i<=r)z[i]=Math.min(r-i+1,z[i-l]);
    while(i+z[i]<a.length&&a[z[i]]===a[i+z[i]])z[i]++;
    if(i+z[i]-1>r){
      l=i;
      r=i+z[i]-1
    }
    s("Extend prefix match",{
      Array:[...a],Z:z,Bounds:[l,r]
    },[i])
  }
  return z
};

Continue learning

Practice related DSA questions in the same topic.