1. Empty pattern
An empty pattern is considered found at index 0.
if (pattern.length === 0) return 0Typorithm · easy
Step 1 of 8 · intro card
Search Algorithms
Naive String Search tries the pattern at every possible text position and compares characters one by one.
Naive String Search is the simplest substring search.
The outer loop chooses a possible start index in the text.
The inner loop compares pattern characters against text characters.
A full pattern match returns the start index; otherwise the search continues.
Try every valid start position.
Compare characters from pattern index 0.
Stop inner loop on mismatch.
Return start index on full match.
Worst-case time is O(n * m).
function naiveStringSearch(text, pattern) {
if (pattern.length === 0) return 0;
for (let i = 0; i <= text.length - pattern.length; i++) {
let j = 0;
while (j < pattern.length && text[i + j] === pattern[j]) {
j++;
}
if (j === pattern.length) return i;
}
return -1;
}Connect each part of the code to the concept before you type.
An empty pattern is considered found at index 0.
if (pattern.length === 0) return 0Try every start index where the full pattern can fit.
for (let i = 0; i <= text.length - pattern.length; i++)j tracks how many pattern characters match.
let j = 0Keep matching while characters agree.
while (j < pattern.length && text[i + j] === pattern[j])Move to the next pattern character after a match.
j++If all pattern characters matched, return the start index.
if (j === pattern.length) return iRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText ababcabc · pattern abc · top row text, bottom row aligned pattern
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state