Problem 68
Find First Occurrence
Easy · 10 pts · String, Two Pointers
Problem
You are given two strings: a haystack H and a needle N. Print the zero-based index where N first appears inside H as a contiguous substring, or -1 if N never appears. Checking every possible starting position and comparing character by character is fast enough for these limits. The KMP algorithm solves it in linear time if you want a challenge.
Input
Two lines: string H and string N (lowercase letters).
Output
Print the zero-based index, or -1.
Constraints
1 <= |H|, |N| <= 10000
Example input
sadbutsad sad
Example output
0
Explanation
The needle "sad" appears in "sadbutsad" at index 0 and again at index 6. The first occurrence is at index 0, so the answer is 0.