← All coding problems
Find the Index of the First Occurrence in a String
easyStrings+10 XPTime limit 3s
Find the index of the first occurrence of needle inside haystack, or -1 if it does not occur.
Input:
- line 1:
haystack - line 2:
needle
Output: the 0-based index, or -1.
Constraints: 1 ≤ length of haystack, needle ≤ 10⁵; lowercase English letters.
Go further: the simple "try every start position" check is O(n·m) in the worst case — the big tests have long runs of the same letter to punish that. Learn KMP (or a rolling hash, Rabin–Karp) for O(n + m).
Sample input 1
sadbutsad sad
Sample output 1
0
Sample input 2
leetcode leeto
Sample output 2
-1
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).