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

Longest Common Prefix visualizer

Learn Longest Common Prefix with a step-by-step Strings visualizer, JavaScript source code and a worked example. Practice fundamentals and parsing.

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
[
  "flower",
  "flow",
  "flight"
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let p=a[0];
for(let i=1;
i<a.length;
i++){
while(!a[i].startsWith(p)){
p=p.slice(0,-1);
s("Shorten prefix",{
Words:a,Prefix:[p]
},[i])
}
}
return p
};

Execution canvas

Active Changed
STEP 1

Shorten prefix

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

Words3 items
Prefix1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Strings · Fundamentals and parsing

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

[
  "flower",
  "flow",
  "flight"
]

Execution steps

  1. Shorten prefix

Computed output

"fl"
JavaScript reference implementation
const solve = (a,s)=>{
  let p=a[0];
  for(let i=1;
  i<a.length;
  i++){
    while(!a[i].startsWith(p)){
      p=p.slice(0,-1);
      s("Shorten prefix",{
        Words:a,Prefix:[p]
      },[i])
    }
  }
  return p
};

Continue learning

Practice related DSA questions in the same topic.