An archivist is digitizing a fragile old manuscript and wants to know exactly where a memorable excerpt she recalls first appears in the fully transcribed text. Given the transcribed manuscript and the excerpt she is looking for, find the earliest position (0-indexed) at which the excerpt occurs as an exact, contiguous run of characters inside the manuscript.
Line 1: the transcribed manuscript, a string text.
Line 2: the excerpt to search for, a string pattern.
A single integer: the 0-indexed position of the first occurrence of pattern within text, or -1 if pattern never occurs in text.
Example 1
Input
thequickbrownfox quick
Expected
3
Explanation
Reading text = "thequickbrownfox" character by character (t=0,h=1,e=2,q=3,u=4,i=5,c=6,k=7,...), the excerpt "quick" begins exactly at index 3 and this is its only (hence earliest) occurrence, so the answer is 3.
Example 2
Input
abcabcabc cba
Expected
-1
Explanation
text = "abcabcabc" only ever contains the length-3 windows "abc", "bca", and "cab" repeating in that cycle; the excerpt "cba" never matches any of them, so the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →