A warehouse scanner records everything that passes on a conveyor belt as one long tape string of characters. A supervisor wants to know where a particular product-code pattern first appears on that tape. Given the tape string and the pattern string, find the smallest starting index (0-indexed) at which the pattern occurs as a contiguous run of characters within the tape. If the pattern never occurs anywhere on the tape, report that instead.
Line 1: the tape string haystack.
Line 2: the pattern string needle.
A single line containing the 0-indexed starting position of the first occurrence of needle inside haystack, or -1 if needle does not occur in haystack.
haystack <= 5000needle <= 5000haystack and needle consist of lowercase English letters only.Example 1
Input
conveyorbelttape belt
Expected
8
Explanation
Scanning "conveyorbelttape" letter by letter, the substring "belt" first begins at index 8 (the letters at positions 8,9,10,11 are b,e,l,t), so the answer is 8.
Example 2
Input
conveyortape belt
Expected
-1
Explanation
The tape "conveyortape" never contains the four consecutive letters "belt" anywhere, 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 →