Find The Index Of The First Occurrence In A String
To solve this coding challenge of finding the index of the first occurrence of
in
, we need to iterate carefully and identify where the substring
first appears within
. The solution must return
if
is not found in
.
Here's a step-by-step explanation of the pseudocode to accomplish this task:
needle
haystack
needle
haystack
-1
needle
haystack
Explanation:
-
Initialize Variables
: Begin by checking for corner cases such as the
needle
needle
0
-
Check if
needle
haystack
needle
haystack
needle
-1
-
Iterate Through
haystack
haystack
needle
-
Compare Substrings
: For each index, extract the substring of
haystack
needle
needle
-
Return First Match
: If a matching substring is found, return its starting index. If loop concludes without finding a match, return
-1
-
Initiate a function
findFirstOccurrence
haystack
needle
-
Check if
needle
0
needle
-
Use a direct membership check (
needle
haystack
needle
haystack
-1
-
Iterate over
haystack
needle
0
length of haystack - length of needle
-
For every iteration, extract a substring from
haystack
i
needle
-
Compare this substring to
needle
i
-
If the loop completes without finding any match, return
-1
needle
haystack
Detailed Steps in Pseudocode:
# Function to find first occurrence of needle in haystack
FUNCTION findFirstOccurrence(haystack, needle)
# Step 1: Handle edge cases where needle is empty
IF needle IS EMPTY
RETURN 0
# Step 2: Check if needle is not part of haystack at all
IF needle NOT IN haystack
RETURN -1
# Step 3: Iterate through haystack with index i
FOR i FROM 0 TO (length of haystack - length of needle)
# Extract substring of haystack
substring = haystack[i : i + length of needle]
# Step 4: Compare extracted substring with needle
IF substring EQUALS needle
RETURN i # Return the start index of the first occurrence
# Step 5: If no match is found, return -1
RETURN -1
Here’s a breakdown of the steps to ensure clarity: