0
Leetcode Problem 28. Find the Index of the First Occurrence in a String
28. Find the Index of the First Occurrence in a String
AI Mock Interview
Leetcode Solutions
Knuth–Morris–Pratt (KMP) Algorithm
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Calculate the length of 'needle' and 'haystack'. If 'needle' is longer than 'haystack', return -1.
Preprocess 'needle' to create the LPS array.
Initialize two pointers, one for 'haystack' and one for 'needle'.
Iterate through 'haystack' using the 'haystack' pointer.
If characters match, increment both pointers.
If they don't match and 'needle' pointer is not at the start, update the 'needle' pointer to the value from the LPS array.
If 'needle' pointer is at the start, increment the 'haystack' pointer.
If the 'needle' pointer reaches the end of 'needle', a match is found; return the start index of the match in 'haystack'.
If no match is found and 'haystack' pointer reaches the end, return -1.
Sliding Window Approach
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...