Loading content...
You are given two strings: a main text string and a pattern string. Your task is to locate the first position where the pattern appears as a contiguous sequence within the text.
Return the starting index (0-based) of the first occurrence of the pattern within the text. If the pattern does not exist anywhere in the text, return -1.
This is a fundamental string matching problem that forms the basis of many text processing algorithms used in search engines, text editors, and data analysis tools.
text = "sadbutsad"
pattern = "sad"0The pattern "sad" appears at indices 0 and 6 within the text "sadbutsad". Since we need the first occurrence, we return index 0.
text = "leetcode"
pattern = "leeto"-1The pattern "leeto" does not appear anywhere in the text "leetcode", so we return -1.
text = "helloworld"
pattern = "world"5The pattern "world" appears starting at index 5 in the text "helloworld".
Constraints