bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 28. Find the Index of the First Occurrence in a String

28. Find the Index of the First Occurrence in a String

Leetcode Solutions

Knuth–Morris–Pratt (KMP) Algorithm

  1. Calculate the length of 'needle' and 'haystack'. If 'needle' is longer than 'haystack', return -1.
  2. Preprocess 'needle' to create the LPS array.
  3. Initialize two pointers, one for 'haystack' and one for 'needle'.
  4. Iterate through 'haystack' using the 'haystack' pointer.
  5. If characters match, increment both pointers.
  6. If they don't match and 'needle' pointer is not at the start, update the 'needle' pointer to the value from the LPS array.
  7. If 'needle' pointer is at the start, increment the 'haystack' pointer.
  8. If the 'needle' pointer reaches the end of 'needle', a match is found; return the start index of the match in 'haystack'.
  9. If no match is found and 'haystack' pointer reaches the end, return -1.
UML Thumbnail

Sliding Window Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...