String Search

String Search

Return the index of the first occurrence of pattern in text, or -1 if it doesn't occur. An empty pattern matches at index 0.

stringSearch(text, pattern)

Input format: text | pattern.

Examples

text="hello world", pattern="world"   // → 6
text="aaaa", pattern="aab"            // → -1
text="abc", pattern=""                // → 0

Walkthrough

Thinking it through

You're looking for the first place the pattern lines up exactly with the text. Checking "does the pattern occur starting here" means comparing character by character from that position. Check every possible starting position, take the first success.

Bounding the search space

The pattern can only fit where enough room remains — starting positions only need to run from the beginning up to where exactly pattern.length characters remain. Trying further right is pointless, since it couldn't fit. This bounds the checks to roughly the text's length.

Building the approach

  1. Handle empty pattern up front: it trivially matches at position 0.
  2. Otherwise, for each candidate start, walk forward comparing text to pattern at the same offset. A mismatch stops this position — move to the next.
  3. A full walk without mismatch means you found the first occurrence — return that position.
  4. No position matches: return -1.

Why this works and where it costs you

This is correct because it's exhaustive within the valid range, trying every position left to right and stopping at the first full match — exactly "first occurrence." It's not the most efficient: repeated near-matches (a long run of the same character) redo comparison work at each shifted position, giving roughly text-length times pattern-length in the worst case. Knuth-Morris-Pratt avoids this by remembering partial-match information, getting to linear time in the combined length. For typical inputs, the straightforward scan is simple, correct, and fast enough.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.