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.
text="hello world", pattern="world" // → 6
text="aaaa", pattern="aab" // → -1
text="abc", pattern="" // → 0
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.
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.
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.
def string_search(text, pattern):
n = len(text)
m = len(pattern)
if m == 0:
return 0
for i in range(n - m + 1):
j = 0
while j < m and text[i + j] == pattern[j]:
j += 1
if j == m:
return i
return -1
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.