Workspace Longest Happy Prefix
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Longest Happy Prefix visualizer

Learn Longest Happy Prefix 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 / 5Execution step
Reference example · JavaScript
Inspect reference input
"level"

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let p=Array(a.length).fill(0),j=0;
for(let i=1;
i<a.length;
i++){
while(j&&a[i]!==a[j])j=p[j-1];
if(a[i]===a[j])j++;
p[i]=j;
s("Update prefix function",{
Array:[...a],LPS:p
},[i])
}
return a.slice(0,p.at(-1))
};

Execution canvas

Active Changed
STEP 1

Update prefix function

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

Array5 items
LPS5 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

"level"

Execution steps

  1. Update prefix function

Computed output

"l"
JavaScript reference implementation
const solve = (a,s)=>{
  let p=Array(a.length).fill(0),j=0;
  for(let i=1;
  i<a.length;
  i++){
    while(j&&a[i]!==a[j])j=p[j-1];
    if(a[i]===a[j])j++;
    p[i]=j;
    s("Update prefix function",{
      Array:[...a],LPS:p
    },[i])
  }
  return a.slice(0,p.at(-1))
};

Continue learning

Practice related DSA questions in the same topic.