Typorithm · easy

Naive String Search

▷ Interactive algorithm labnaive-string-searchsearchstringpatternnested-loops
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Naive String Search

0%

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.

Preparing algorithm lab…
01

Try every valid start position.

02

Compare characters from pattern index 0.

03

Stop inner loop on mismatch.

04

Return start index on full match.

05

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Empty pattern

An empty pattern is considered found at index 0.

if (pattern.length === 0) return 0

2. Start positions

Try every start index where the full pattern can fit.

for (let i = 0; i <= text.length - pattern.length; i++)

3. Pattern pointer

j tracks how many pattern characters match.

let j = 0

4. Compare characters

Keep matching while characters agree.

while (j < pattern.length && text[i + j] === pattern[j])

5. Advance pattern

Move to the next pattern character after a match.

j++

6. Full match

If all pattern characters matched, return the start index.

if (j === pattern.length) return i

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Naive String Search: Visual Walkthrough & Practice · Typorithm | ApplyDjinn