FIND THE INDEX OF THE FIRST OCCURRENCE IN A STRING

Опубликовано: 16 Май 2026
на канале: One Person Studio
34
4

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

EXPLANATION CODE:
1) The strStr method is an implementation of the string searching algorithm known as "needle in a haystack" or string matching. It aims to find the starting index of the needle string within the haystack string.

2) The needle string's empty state is first checked in the procedure. If it is, it indicates that the haystack's first needle has been located, and it returns 0.

3) If the needle string is not empty, the method proceeds with a nested loop. The outer loop iterates over the possible starting indices in the haystack string.

4) The inner loop iterates over the characters in the needle string for each beginning index.

5) Inside the inner loop, the code compares the characters at the corresponding positions in both the haystack and needle. If any characters don't match, the inner loop is broken using the break statement.

6) If the inner loop completes without encountering any mismatches (i.e., all characters match), the method returns the current starting index i, indicating the position where the needle is found in the haystack.

7) If the outer loop finishes without finding a match, the method returns -1 to indicate that the needle is not present in the haystack.
#leetcode #leet #code #softwareengineer #software #engineer #programmingchallenge #programming #challenge #difficulty #easy #python #pythonprogramming #find #the #index #of #the #first #occurrence #string #explanation #asmr #typing #datastructures #technicalinterview #technical #interview

Contents:
0:00 - Reading
1:05 - Solving
2:20 - Explaining