Workspace Find First Occurrence In A String
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Find First Occurrence in a String visualizer

Learn Find First Occurrence in a String 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 / 4Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": "sadbutsad",
  "b": "sad"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,b
},s)=>{
for(let i=0;
i+b.length<=a.length;
i++){
let j=0;
while(j<b.length&&a[i+j]===b[j]){
s("Match character",{
Text:[...a],Pattern:[...b],Position:[i,j]
},[i+j]);
j++
}
if(j===b.length)return i
}
return -1
};

Execution canvas

Active Changed
STEP 1

Match character

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

Text9 items
Pattern3 items
Position2 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

{
  "a": "sadbutsad",
  "b": "sad"
}

Execution steps

  1. Match character

Computed output

0
JavaScript reference implementation
const solve = ({
  a,b
},s)=>{
  for(let i=0;
  i+b.length<=a.length;
  i++){
    let j=0;
    while(j<b.length&&a[i+j]===b[j]){
      s("Match character",{
        Text:[...a],Pattern:[...b],Position:[i,j]
      },[i+j]);
      j++
    }
    if(j===b.length)return i
  }
  return -1
};

Continue learning

Practice related DSA questions in the same topic.